What's the proper way to cancel all JS setTimeout , setInterval and requestAnimationFrame after a given amount of seconds ?
Edit: Sorry, I should have explained more! The code comes from either Database or some API, so I cannot keep track of the timeout,raf or interval IDs. So I don't have the IDs of the timers that I can easily you to clearInterval or clearTimeout or cancelAnimationFrame. I know I have to use them, but I don't know how to get all the animation IDs (if there are any).
To clear all timeouts they must be "captured" first: Place the below code before any other script and it will create a wrapper function for the original setTimeout & clearTimeout . 💡 New clearTimeouts methods will be added to the window Object, which will allow clearing all (pending) timeouts (Gist link).
Answer: Use the clearInterval() Method The setInterval() method returns an interval ID which uniquely identifies the interval. You can pass this interval ID to the global clearInterval() method to cancel or stop setInterval() call.
It will clear all the timeouts, as setTimeout is an Asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack, thus clearAllTimeout runs and cancels them before they can be executed.
You need to keep the Id of each interval, timeout and requestAnimationFrame you've created and call window.clearInterval(id)
etc. on them.
A verfy hackish/brute force way to do it would be something like:
for (var i = 1; i < 99999; i++) {
window.clearInterval(i);
window.clearTimeout(i);
window.mozCancelAnimationFrame(i); // Firefox
}
But I wouldn't recommend that.
Update:
To do it after a certain amount of time:
setTimeout(function () {
for (var i = 1; i < 99999; i++) {
window.clearInterval(i);
window.clearTimeout(i);
window.mozCancelAnimationFrame(i); // Firefox
}
}, 3000); // After 3 seconds
Update 2:
I don't believe there is a better way than the brute force way if you don't keep a reference for each time out etc, so to make it a bit easier to do that (as suggested by this SO answer), you could override the default setInterval:
var intervals = new Array();
window.oldSetInterval = window.setInterval;
window.setInterval = function(func, interval) {
intervals.push(oldSetInterval(func, interval));
}
// Now you can loop over intervals and clear them
// one by one when ever you want to.
for (var interval in intervals) {
window.clearInterval(interval);
}
The example shows how to do it for setInterval
, but could of course be done the same way on setTimeout
and requestAnimationFrame
as well.
You'll need to obtain references to each timeout (the return value of setTimeout
) then use clearTimeout()
then you wish you cancel them. Same for setInterval.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With