有没有办法一次清除所有 JavaScript 计时器? [英] Is there a way to clear all JavaScript timers at once?
问题描述
我正在使用 jQuery .load 为我的网站构建一个自动刷新的评论部分.所以我使用 javascript 'setTimeout' 计时器来检查新评论.
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.
但是在执行诸如更改评论页面或删除(全部使用 ajax)之类的操作后,一些旧计时器继续运行,即使我在加载新的 ajax 内容之前使用了 clearTimeout.
But after doing some stuff like changing comment pages or deleting (all using ajax), a few old timers keep running, even though I used clearTimeout before loading new ajax content.
有什么方法可以在我加载新的 ajax 内容时清除所有 javascript 计时器?
Is there some way to clear ALL javascript timers when I load new ajax content?
推荐答案
javascript 中没有允许您清除所有计时器的通用函数.您将需要跟踪您创建的所有计时器.为此,您可以使用全局数组:
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]);
}
这篇关于有没有办法一次清除所有 JavaScript 计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!