I want to resume the game after pausing it, and it freezes the game, but after resuming, the game only gives you one key and the score is glitching between 0 and whatever score you actually have.
I tried using the clearTimeout() function to stop the function, store the timer, lives, score, and current key, however it seems to stuck on the one key I gave it.
This is the pause function:
function pause() {
window.addEventListener("keydown", (event) => {
if (event.key == 'Tab') {
if (!isPaused) {
isPaused = true;
gameIsPlaying = false;
window.currentKey = item
window.currentScore = score
window.currentTime = seconds
window.currentLives = lives
console.log(currentKey, currentScore, currentTime)
clearTimeout(timerId);
clearTimeout(updateLives);
clearTimeout(ScoreUpdate);
bars.forEach((bar) => {
bar.style.animationPlayState = 'paused';
})
AudioElement.pause();
} else {
isPaused = false;
item = currentKey
score = currentScore
seconds = currentTime
lives = currentLives
game(item, seconds, lives, score);
bars.forEach((bar) => {
bar.style.animationPlayState = 'running';
})
AudioElement.play();
}
}
})
}
JSFiddle: https://jsfiddle.net/b30osaLp/ (Tab to Pause game)
Edit: I tried @code's solution in the comments.
window.addEventListener("keydown", (event) => {
if (event.key == 'Tab') {
pause();
}
})
function pause() {
if (!isPaused) {
isPaused = true;
gameIsPlaying = false;
clearTimeout(timerId);
clearTimeout(updateLives);
clearTimeout(ScoreUpdate);
bars.forEach((bar) => {
bar.style.animationPlayState = 'paused';
})
AudioElement.pause();
} else {
isPaused = false;
game();
bars.forEach((bar) => {
bar.style.animationPlayState = 'running';
})
AudioElement.play();
}
}
But it still is producing the same issue.
isPaused, accessible in scope both bypause()and your event listener handler, then have your event listener handler check whether it's paused each time it's fired to decide whether to execute.letter(), two new event listeners are added. Every timegame()is called, an event listener for pause is created. You need to refactor these from thegame()method.