“未捕获的TypeError:回调不是函数”-为什么我得到这个?

时间:2018-10-12 04:47:52

标签: javascript callback runtime-error

我正在尝试在javascript中创建“打字机”效果,使它看起来像“拼写”,然后从数组中“删除”单词。我有一个拼写每个单词的“拼写”功能,我想在“删除”功能中添加一个回调,以便一旦单词输入完毕,它将开始删除。

但是,当我尝试附加回调时,仍然出现以下错误:

main.js:35 Uncaught TypeError: callback is not a function
   at spell (main.js:35)
   at main.js:32

它参考以下代码块中的倒数第二行:

// SPELL OUT WORD FUNCTION
function spell(x, callback, length) {
    setTimeout(() => {
        wordBox.innerHTML += letterArray[wordLength - x];
        if (--x) spell(x);
    }, randTime);

    callback(length);       // <--- THIS IS THE ERROR
    }

我认为该代码也可能引起该错误,在此我调用了“拼写”功能,但我不确定:

// CALL ADD WORD FUNCTION
spell(wordLength, remove, wordLength);

我还附加了下面的整个代码块。任何意见是极大的赞赏。干杯!

const words = [
    'creator.'
];

// START TYPEWRITER ON LOAD
window.addEventListener('load', typewriter);

function typewriter() {

    // LOOP FOR EACH WORD IN ARRAY
    for (let i = 0; i < words.length; i++) {
        const word = words[i];
        const wordLength = word.length;
        const letterArray = [];
        const wordBox = document.querySelector('#text');

        var timeArray = [500, 600, 700, 800];
        var randTime = timeArray[Math.floor(Math.random() * timeArray.length)];
        var deleteDelay = 300;
        var iterationDelay = 1000;


        // CREATE LETTER ARRAY
        for (let i = 0; i < wordLength; i++) {
            letterArray.push(word.charAt(i));
        }

        // SPELL OUT WORD FUNCTION
        function spell(x, callback, length) {
            setTimeout(() => {
                wordBox.innerHTML += letterArray[wordLength - x];
                if (--x) spell(x);
            }, randTime);

            callback(length);
        }

        // DELETE LETTERS FROM WORD FUNCTION
        function remove(y) {
            setTimeout(() => {
                const string = wordBox.textContent;
                const newString = string.substring(0, string.length - 1);
                wordBox.textContent = newString;
                if (--y) remove(y);
            }, deleteDelay);
        }

        // CALL ADD WORD FUNCTION
        spell(wordLength, remove, wordLength);
    }
}

0 个答案:

没有答案