Is there a way to clear all JavaScript timers at once?

后端 未结 4 1782
夕颜
夕颜 2020-12-28 15:30

Im building an automatic refreshing comment section for my website using jQuery .load. So I am using a javascript \'setTimeout\' timer to check for new comments.

But

4条回答
  •  天命终不由人
    2020-12-28 16:28

    There's no general function in javascript that allows you to clear all timers. You will need to keep track of all timers you create. For this you could use a global array:

    var timers = [];
    ...
    // add a timer to the array
    timers.push(setTimeout(someFunc, 1000));
    ...
    // clear all timers in the array
    for (var i = 0; i < timers.length; i++)
    {
        clearTimeout(timers[i]);
    }
    

提交回复
热议问题