Clear All Intervals & Timeouts
There isn’t a JavaScript built-in method for clearing all timeouts and intervals – which can be frustrating when you’re building a complex system that relies heavily on Ajax and interval/timeout calls.
The solution is actually fairly simple – assuming you don’t need to keep track of each interval/timeout separately.
The best method that I’ve come up with is to store each timeout and interval in an Array
, and then when you want to clear those timeouts & intervals, you just walk through the array and clear each individually. I’m going to make the assumption that you’re using jQuery; however, this can translate into any library you use, or just basic JavaScript if that’s your preference.
For example:
var myIntervals = [];
var myTimeouts = [];
$(function(){
// create some sort of timeout event
myTimeouts[myTimeouts.length] = setTimeout(function() { myTimeoutFunction(); }, 2000);
// create some sort of interval event
myIntervals[myIntervals.length] = setInterval(function() { myIntervalFunction(); }, 2000);
$(document).on('click', '.someClass', function(){
clearAllTimeouts();
clearAllIntervals();
});
});
function myTimeoutFunction() {
... do something here
}
function myIntervalFunction(){
... do something here
}
function clearAllTimeouts() {
for (x=0; x<myTimeouts.length; x++) {
clearTimeout(myTimeouts[x]);
}
}
function clearAllIntervals() {
for (x=0; x<myIntervals.length; x++) {
clearTimeout(myIntervals[x]);
}
}
That’s it – you can store every interval/timeout call in these Arrays
– it’s a one-function call to clear them all. It’s likely more useful for interval calls as they aren’t a one-run call like timeout is.