How Can I Disable All SetTimeout Events?
Solution 1:
If you can't get access to the code where the timer is set Nick's answer may not work, so all that I can think of is this hack.
It is a hack, use with caution!
// Set a fake timeout to get the highest timeout id
var highestTimeoutId = setTimeout(";");
for (var i = 0 ; i < highestTimeoutId ; i++) {
clearTimeout(i);
}
Basically it 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!
Solution 2:
When you call setTimeout()
, store the timer ID so you can clear it. If you're creating many timeouts, then an array is a good option for storing the IDs. For example:
var timeouts = [];
//then, store when you create them
timeouts.push( setTimeout( { ... }, 1000) );
Then when you want to clear them:
for (var i = 0; i < timeouts.length; i++) {
clearTimeout(timeouts[i]);
}
//quick reset of the timer array you just cleared
timeouts = [];
As @Robert noted below, clearTimeout()
won't throw an error if the timeout has already occurred, so there are no race/timing issues here.
Solution 3:
Not sure if you can do this globally, but the most common method is to use clearTimeout. You pass the return value of setTimeout() to clearTimeout(), you could use a global var to store all timeout vars.
Solution 4:
Firstly, I was using this code:
var x = setTimeout('');
for (var i = 0; i < x; i++)
clearTimeout(x);
However, this peace of code did not work on Google Chrome. So I made improvement for this:
var x = setTimeout('alert("x");',100000); //It is very low probability that after 100 seconds x timeout will not be cleared
for (var i = 0; i <= x; i++)
clearTimeout(i);
Finally, it is a hack, as it was mentioned in the comment above, so use it carefully.
Edit: fixed wrong variable used in loop (use i instead of x)
Solution 5:
you can stop setTimeout()
of one function in other function using clearTimeout()
var myVar;
function myFunction() {
myVar = setTimeout(function(){ alert("Hello"); }, 3000);
}
function myStopFunction() {
clearTimeout(myVar);
}
Post a Comment for "How Can I Disable All SetTimeout Events?"