我的目标是每四秒钟显示一次数组中的单词,除非用户在不到四秒钟的时间内正确输入单词,在这种情况下,间隔会被清除并重新启动。当我单击“开始”时,会在单词显示前四秒钟过去。我希望它立即显示,此后每隔四秒显示一次,除非用户在四秒之前键入正确的单词,在这种情况下,清除间隔并重新启动间隔,在这种情况下,在显示下一个单词之前会有四秒钟的延迟。为什么间隔在执行操作之前要经过一次计数。我怎样才能解决这个问题?我对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();
}
答案 0 :(得分:-1)
您可以使用 setTimeout 和 clearTimeout 重置
var tmr;
function startTimer() {
tmr = setTimeout(showWord, 4000);
}
function stopTimer() {
if(tmr) {
clearTimeout(tmr);
}
}