How can I disable all setTimeout events?

蓝咒 提交于 2019-11-28 15:28:17
Nick Craver

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.

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!

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.

Vaidotas Strazdas

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!