javascript - setInterval 有效但延迟了一个周期

标签 javascript setinterval

<分区>

我的目标是每四秒显示一次数组中的一个词,除非用户在不到四秒的时间内正确键入该词,在这种情况下,间隔将被清除并重新启动。当我单击开始时,在显示单词之前四秒钟过去了。我希望它立即显示,此后每四秒显示一次,除非用户在四秒之前键入正确的单词,在这种情况下,间隔被清除并重新启动,在这种情况下,在显示下一个单词之前有四秒的延迟。为什么interval跑完count一次才执行 Action 。我怎样才能解决这个问题?我不熟悉jquery所以请在js中提供一些建议`

startBtn.addEventListener('click', startGame);
answerBox.addEventListener('keyup', checkWord);


function startGame() {
    //showWord();
    gameTimer = setInterval(gameTime, 1000);
    timedWordDisplay = setInterval(showWord, 4000);
    }



function checkWord() {
    let currentWordLen = answerBox.value.length;
    if (wordDisplayBox.innerHTML === answerBox.value) {
        clearInterval(timedWordDisplay);
        numWordsRight++;
        numGoodWordsField.innerHTML = numWordsRight;
        answerBox.value = '';
        answerBox.focus();
        wordDisplayBox.innerHTML = '';
        timedWordDisplay = setInterval(showWord, 4000);
    } else if (answerBox.value === currentWord.substring(0, currentWordLen)) {
             answerBox.style.borderColor = 'green';
    } else {
      answerBox.style.borderColor = 'red';
    }
    
        
    
}

/* function checkWord() {
    let currentWordLen = answerBox.value.length;
    if (wordDisplayBox.innerHTML === answerBox.value) {
        clearInterval(showWord);
        goodScore++;
        numGoodWordsField.innerHTML = goodScore;
        answerBox.value = '';
        answerBox.focus();
        setInterval(showWord,4000);
    } else if (answerBox.value === currentWord.substring(0,currentWordLen)) {
      answerBox.style.backgroundColor = 'green';
    } else {
      answerBox.style.backgroundColor = 'red';
    }
    
}
*/

function showWord() {
    answerBox.focus();
    console.log('show word func start');
    console.log('seconds between ' + time);
    let randomNum = Math.floor(Math.random()*wordsLevelOne.length);
        console.log('random number is:' + randomNum);
    currentWord = wordsLevelOne[randomNum];
    console.log('curentWord is ' + currentWord);
    wordDisplayBox.innerHTML = currentWord;
    //setInterval(wordTime, 1000);
    //showWord();
}

最佳答案

您可以使用setTimeoutclearTimeout 来重置

var tmr;
function startTimer() {
    tmr = setTimeout(showWord, 4000);
}

function stopTimer() {
    if(tmr) {
        clearTimeout(tmr);
    }
}

关于javascript - setInterval 有效但延迟了一个周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54282417/

相关文章:

javascript - iOS 6 Safari ,setInterval 不会被解雇

javascript - Safari 和 Chrome 中的 iframe 问题

javascript - 为什么API的内容显示不出来?

javascript - global.process 的构造函数是否存储在除 global.process.constructor 之外的任何位置?

javascript - 关闭存储在计时器/Websocket 客户端对数组中的 JavaScript setInterval 计时器

Javascript setInterval 有效但不是无限循环

javascript - 计数和倒计时循环

javascript - HTML 在新窗口中

javascript - Onblur功能持续运行

JavaScript setInterval() 性能