How to stop a requestAnimationFrame recursion/loop?
One way to start/stop is like this
var requestId;function loop(time) { requestId = undefined; ... // do stuff ... start();}function start() { if (!requestId) { requestId = window.requestAnimationFrame(loop); }}function stop() { if (requestId) { window.cancelAnimationFrame(requestId); requestId = undefined; }}
Working example:
Stopping is as simple as not calling requestAnimationFrame anymore, and restarting is to call it it again.ex)
var pause = false; function loop(){ //... your stuff; if(pause) return; window.requestionAnimationFrame(loop); } loop(); //to start it off pause = true; //to stop it loop(); //to restart it
I would suggest having a look at the requestAnimationFrame polyfill gibhub page. There are discussions about how this is implemented.