问题描述
我正在像这样的each()
函数中使用setIntervals
I'm using setIntervals
within an each()
function like so
$(".elements").each(function() {
setInterval(function() {
}, 1000);
});
显然,为每个元素创建了一个setIntervals.
Obviously a setIntervals is created for each element.
我的问题是:当我不再需要所有setIntervals时,该如何清除它们?我试过将setInterval存储在变量中并调用window.clearInterval(int)
,但这仅清除了最后一个setInterval,因为每个变量都被覆盖.
My question is: How do I clear all the setIntervals when I no longer need them? I have tried storing the setInterval in a variable and call window.clearInterval(int)
, but that only clears the last setInterval since each variable is overridden.
推荐答案
设置时间间隔后,您将获得一个指向它的指针:
When you set an interval, you get a pointer to it:
var myInterval = setInterval(function(){}, 4000);
如果要取消间隔,请执行以下操作:
If you want to cancel an interval, you do the following:
clearInterval(myInterval);
因此,对于您想做的事情,您将执行以下操作:
So, for what you want to do, you would do the following:
var intervals = [];
$(".elements").each(function() {
var i = setInterval(function() {
}, 1000);
intervals.push(i);
});
然后,如果您需要取消它们,则可以执行以下操作:
Then if you need to cancel them all you can do this:
intervals.forEach(clearInterval);
那应该为您做.
这篇关于清除所有setIntervals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!