How can I disable all setTimeout events?

北慕城南 提交于 2019-11-27 19:46:42

问题


I am using ajax and asp.net. iI have a javascript function which creates many other javascript functions with setTimeout. After asynchronous postback happenes, I want to disable all of these setTimeouted events. How can I do that?


回答1:


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.




回答2:


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!




回答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.




回答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)



来源:https://stackoverflow.com/questions/3847121/how-can-i-disable-all-settimeout-events

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