Reputation: 69
So, I'm having an issue with figuring out how to pause and (most importantly) unpause my simulation. When I press play, I call a function called animate(). I only call it once, so naturally inside animate() I call requestAnimationFrame(animate) for it to loop as usual:
function animate() {
idAnimate = requestAnimationFrame(animate);
(...more code...)
}
Note that I'm attibuting the return to idAnimate so I can use it as argument for cancelAnimationFrame(idAnimate) wherever I need it. My problem is that, once I'm able to stop the animation, I cannot unpause it back. I've searched for alternatives, like using a boolean variable like isPaused and only calling requestAnimationFrame when isPaused is false, but as far as I understand when isPaused becames true the animation loop stops and it can no longer test if it's true or not. I only call animate() once, so once it's out of the loop it no longer enters it. No matter how I pause it (either by making isPaused true or calling externally cancelAnimationFrame(idAnimate)), I can't seem to make it go back.
I'd love some insight on this. I hope I was able to make myself clear. Thank you in advance! :)
Upvotes: 2
Views: 2416
Reputation: 3
The reason he is having trouble with this and why other answers will not work for him, is that all his code is inside the loop. Which means that once the loop stops, it can't check again for the unpause.
The way to do it is to then run the loop again through another mean, like through a click event. I.e. once the player clicks the screen, call the loop again
addEventListener("mousedown", function (event) {
if (isPaused){
animate()
}
});
Upvotes: 0
Reputation: 2763
One of solution.
You have flag variable like isRunning.
When you start then you set isRunning to true. When you stop you set is running to false and break loop. On the end of loop you call it by requestAnimationFrame again. Loop function call additionaly function animating next step of animation.
let isRunning = false
function loop(){
if(!isRunning)
return
setNextColor();
requestAnimationFrame(loop)
}
function start(){
isRunning = true
loop();
}
function stop(){
isRunning = false
}
let hue = 0
const box = document.getElementById("box")
function setNextColor(){
hue++
box.style.backgroundColor = `hsl(${hue},100%,30%)`;
}
<div id="box">
<button onclick="start()">start</button>
<button onclick="stop()">stop</button>
Upvotes: 4