How can I disable all setTimeout events?

前端 未结 4 1833
清酒与你
清酒与你 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条回答
  •  Happy的楠姐
    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.

提交回复
热议问题