I’ve been making ping pong game watching tutorial and in the end decided to enhance a bit by adding paused button, I added and everything worked just fine but when I restart the game it was still being paused. Then I decided that I needed to add a paused check variable paused = false;
and for some reason the state is the same, please help me!
const resetBtn = document.querySelector('#resetBtn');
const pauseBtn = document.querySelector('#pauseBtn');
paused = false;
running = true;
pauseBtn.addEventListener('click', pauseGame);
resetBtn.addEventListener('click', resetGame);
gameStart();
function gameStart(){
createBall();
nextTick();
};
function nextTick(){
if(running && !paused){
intervalID = setTimeout(() => {
// some code
nextTick();
}, 10)
}
else{
displayPause();
}
};
function resetGame(){
// some code
paused = false;
// some code
updateScore();
clearInterval(intervalID);
gameStart();
};
function pauseGame(){
running = !running;
paused = true;
if(running){
nextTick();
}
};
<button class="buttons" id="pauseBtn">pause</button>
<button class="buttons" id="resetBtn">reset</button>
I’m expecting to resume game when user press restart button.
2
Answers
the issue is resoled, i actually didn't need another variable like paused, all i needed was to add running to true like below, thanks for your attention
};
You don’t need both a
running
andpaused
variable. They are essentially the same thing. Just userunning
since you’ve already got that working.Since you are using
setTimeout
to run your game, you need to useclearTimeout
when to clear it, notclearInterval
. If you were usingsetTinterval
that’s when you’d want to useclearInterval
to clear it.In the below code I’ve changed your timeout amount to
100
just so it’s easier to see what’s happening in the console, it goes by too quickly at10
. You should probably keep it at10
for your game though