Sometimes, we want to stop a requestAnimationFrame recursion or loop with JavaScript.
In this article, we’ll look at how to stop a requestAnimationFrame recursion or loop with JavaScript.
How to stop a requestAnimationFrame recursion or loop with JavaScript?
To stop a requestAnimationFrame recursion or loop with JavaScript, we can add a flag to check when to stop calling requestAnimationFrame
.
For instance, we write
let pause = false;
const loop = () => {
//...
if (pause) {
return;
}
window.requestionAnimationFrame(loop);
};
loop();
pause = true;
loop();
to define the loop
function that returns before calling requestionAnimationFrame
if pause
is true
.
Then we call loop
before and after we set pause
to true
.
Therefore, the first loop
call will call requestionAnimationFrame
and the 2nd one won’t.
Conclusion
To stop a requestAnimationFrame recursion or loop with JavaScript, we can add a flag to check when to stop calling requestAnimationFrame
.