How can I disable all setTimeout events?

前端 未结 4 1828
清酒与你
清酒与你 2020-12-12 12:12

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 dis

相关标签:
4条回答
  • 2020-12-12 12:42

    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.

    0 讨论(0)
  • 2020-12-12 12:48

    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)

    0 讨论(0)
  • 2020-12-12 12:52

    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.

    0 讨论(0)
  • 2020-12-12 12:54

    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!

    0 讨论(0)
提交回复
热议问题