【问题标题】:setInterval works but delayed one cycle [duplicate]setInterval 有效但延迟了一个周期[重复]
【发布时间】:2019-06-14 09:32:15
【问题描述】:

我的目标是每四秒显示一次数组中的一个单词,除非用户在不到四秒的时间内正确键入了该单词,在这种情况下,间隔被清除并重新启动。当我单击开始时,在显示单词之前四秒钟过去了。我希望它立即显示并在此后每四秒显示一次,除非用户在四秒之前键入正确的单词,在这种情况下,间隔被清除并重新启动,在这种情况下,在显示下一个单词之前有四秒的延迟。为什么间隔在执行操作之前会经过一次计数。我怎样才能解决这个问题?我对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();
}

【问题讨论】:

  • 在设置间隔前请致电showWord()
  • 谢谢你,马克。它现在可以在正确的时间运行。为什么 setInterval 似乎要等待一段时间(在我的情况下为 4000 毫秒)才能执行其中调用的函数?
  • 因为 setInterval 实际上是一个递归 setTimeout(至少在规范中,一些实现使用偏移校正递归 setTimeout 使其更加复杂,但我离题了)。

标签: javascript setinterval


【解决方案1】:

您可以使用 setTimeoutclearTimeout 来重置

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多