frosty frosty - 2 months ago 11
Javascript Question

HTML5 Canvas – Stop previous requestAnimationFrame

I'm using HTML Canvas. I want new frames to be requested only if the click function hasn't been fired again. Basically I want it to "stop" the previous recursiveness, I think

document.addEventListener('click', function(){

[...]

var animate = function() {
if (the click event was NOT fired again) {
requestAnimationFrame(animate);
}
};
animate();

});


How would I do this?

Answer

You can set a global variable like rafId and in the line you invoke rAF make it like;

rafId = requestAnimationFrame(animate);

then when needed invoke cancelAnimationFrame() like cancelAnimationFrame(rafId)