如何清除setInterval的所有实例
How to clear all instances of a setInterval?
setInterval:
$('li.item').live('click', function(){
//Need to work with Dyn created object
//clearInterval(itemClockInterval);
itemClockInterval = setInterval(function() {
deconInterval(_this.children('.timeleft'), time);
}, 1000);
});
类"item"有多个li。当单击setInterval函数时,更新附加到特定li的时钟。
我的问题是,每次an li被点击,时钟倒计时的速度是以前的两倍,因为一个额外的间隔正在运行。我需要在新的间隔开始之前清除间隔的所有实例,但是我的解决方案都不起作用。
我注释掉了我尝试过的一件事,看到间隔直到后来才创建,这是有问题的。
使用。data()将setInterval()的结果存储在元素上,并在单击时清除。
$('li.item').live('click', function(){
$this = $(this);
var existing_timer = $this.data('clock');
if (existing_timer){
clearInterval(existing_timer);
}
itemClockInterval = setInterval(function() {
deconInterval($this.children('.timeleft'), time);
}, 1000);
$this.data('clock', itemClockInterval);
});
使用闭包:
$('li.item').live('click', (function(){ //Need to work with Dyn created object
var itemClockInterval;
return function(){
if(itemClockInterval) clearInterval(itemClockInterval);
itemClockInterval = setInterval(function() {
deconInterval(_this.children('.timeleft'), time);
}, 1000);
};
})());
或者,使用jQuery的data方法:
$('li.item').live('click', function(ev){ //Need to work with Dyn created object
var itemClockInterval = $(ev.target).data("itemClockInterval")
if(itemClockInterval) clearInterval(itemClockInterval);
$(ev.target).data("itemClockInterval", setInterval(function() {
deconInterval(_this.children('.timeleft'), time);
}, 1000));
});
使用数据存储与该li…
$('li.item').live('click', function(){ //Need to work with Dyn created object
var itemClockIntervalID = $(this).data("itemClockIntervalID");
if (itemClockIntervalID != "undefined") {
clearInterval(itemClockIntervalID);
}
itemClockIntervalID = setInterval(function() { deconInterval(_this.children('.timeleft'), time); }, 1000);
$(this).data("itemClockIntervalID", itemClockIntervalID);
});
或者使用jQuery的功能为您跟踪计时器,如下所述:http://plugins.jquery.com/project/timers。它会自动维护一个jQuery对象和你的计时器之间的关联,所以它会跟踪以前的计时器,这样你就可以在设置一个新的计时器之前清除间隔。
相关文章:
- ES6构造函数返回基类的实例
- node.js:setInterval()正在跳过调用
- KnockoutJS-组件-多个实例
- 为什么无法在TypeScript中导出类实例
- 如何在GoogleWeb工具包(GWT)中从JSNI调用接口(实例化)
- fluxxor向一个flux实例添加一组以上的操作
- 使用jQuery获取Dropzone实例/对象
- "实例范围”;TypeScript类的getter/setter
- 如何在速度模板中获取LiferayPortlet实例id
- 同一项怎么可能在一个实例中未定义,却在另一个实例上定义
- 实例创建(JS)
- setInterval和clearInterval javascript无法按需工作
- 如何在javaScript中实例化使用setInterval的对象
- 为什么重置 setInterval 它继续调用多个函数实例而不是一个
- 使用setInterval的多个实例
- 美元(文档).ready + setInterval =多个实例正在运行
- 如何清除setInterval的所有实例
- 清除使用setInterval创建的变量的多个实例
- 请确保特定的setInterval函数实例只运行一次
- Setinterval的多个实例