my goal is to display a word from the array every four seconds unless the user types the word correctly in less than four seconds in which case the interval is cleared and restarted. when i click start four seconds pass before the word is displayed. i want it to show immediatly and every four seconds thereafter unless the user types the correct word before four seconds in which case the interval is cleared and restarted and in that case there is a four second delay before the next word is shown. Why is it that the interval runs through the count once before performing the action. How can i fix this? I am not familiar with jquery so please some advice in 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();
}