I'm working on an ajax web appliation which contains many running timeouts and intervals. And now I need to clear all running timeouts and intervals sometimes. Is there a simple way to stop everything without need to store every timeout and interval ID and iterate through them and clear them?
The clearInterval() method clears a timer set with the setInterval() method.
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.
function doSomething() { console. log("10 seconds"); setTimeout(doSomething, 10000); } setTimeout(doSomething, 10000); Or if you don't want to declare a separate function and want to stick with a function expression you need to make it a named function expression: setTimeout(function doSomething() { console.
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).
Sometimes it's possible to save the timer Id / Handle to clear it later which would be the best solution. So this is a second best. But I wanted to give a better understanding of what's going on. It basically grabs the highest timer id and clears everything less than that. But it's also possible to clear other timers that you do not want to clear!
It is a little hackish, so be warned!
// Set a fake timeout to get the highest timeout id var highestTimeoutId = setTimeout(";"); for (var i = 0 ; i < highestTimeoutId ; i++) { clearTimeout(i); }
Updated answer after reading the duplicate I closed this question with -
It works and tested in Chrome on OSX
// run something var id1 = setInterval(function() { console.log("interval", new Date())}, 1000); var id2 = setTimeout(function() { console.log("timeout 1", new Date())}, 2000); var id3 = setTimeout(function() { console.log("timeout 2", new Date())}, 5000); // not run setTimeout(function() { console.log("timeout 3", new Date())}, 6000); // not run // this will kill all intervals and timeouts too in 3 seconds. // Change 3000 to anything larger than 10 var killId = setTimeout(function() { for (var i = killId; i > 0; i--) clearInterval(i) }, 3000); console.log(id1, id2, id3, killId); // the IDs set by the function I used
NOTE: Looked at window objects that had a typeof number - funnily enough IE assigns an 8 digit number, FF a single digit starting with 2
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