使用多个 setInterval 实例 [英] Using multiple instances of setInterval
问题描述
我这里有一个 jsFiddle:http://jsfiddle.net/dztGA/22/
I have a jsFiddle here: http://jsfiddle.net/dztGA/22/
目标:本质上,我试图在同一页面上有 2 个离散计时器,它们可以在鼠标悬停/鼠标移开(暂停)或手动进程(重新启动)时被销毁和重新创建).
The goal: Essentially, I'm trying to have 2 discrete timers on the same page that can be destroyed and re-created on mouseover/mouseout (pause), or on manual progression (restart).
问题:我的 jsFiddle 的单个计时器将说明的是,当我单击停止计时器"时,我的 setInterval(存储在变量 t 中)似乎有多个实例,尽管被 clearInterval(t).当我单击重新启动计时器"时,这变得很明显,它似乎有 2 个以上的独立计时器,如快速增量所示.
The problem: What my jsFiddle's single timer will illustrate is that when I click "Stop Timer", my setInterval (stored in variable t) seems to have multiple instances albeit being destroyed with clearInterval(t). This becomes apparent when I click "Restart Timer" and it seems to have 2+ independent timers as illustrated by the quick increment.
警告:我已经尽可能多地研究了 SO,但是因为我将在页面上有 2 个不同的滑块,所以我不能使用任何清除所有计时器"方法,所以我尝试将每个方法存储在一个变量中.
A caveat: I have done as much research on SO as I can, but because I'll be having 2 different sliders on the page, I can't use any "clear all timers" methods, so I tried storing each in a variable.
我希望这很清楚.感谢观看.
I hope that's clear. Thanks for the view.
推荐答案
要解决您当前的问题:在 onclick
函数中添加 clearInterval(window.t)
重置按钮.
To fix your current issue: Add clearInterval(window.t)
at the onclick
function of the reset button.
一种能够拥有多个计时器的方法.不过,这需要一定的结构.
小提琴(6 个计时器!):http://jsfiddle.net/dztGA/27/
A method to be able to have multiple timers. This requires a certain structure, though.
Fiddle (6 timers!): http://jsfiddle.net/dztGA/27/
(function(){ //Anonymous function, to not leak variables to the global scope
var defaultSpeed = 3000; //Used when missing
var timerSpeed = [500, 1000, 2000, 4000, 8000];
var intervals = [];
function increase(i){
return function(){
var elem = $("#count"+i);
elem.text(parseFloat(elem.text()) + 1);
}
}
function clear(i){
return function(){
clearInterval(intervals[i]);
}
}
function restart(i){ //Start AND restart
return function(){
clear(i)();
increase(i)();
intervals[i] = setInterval(increase(i), timerSpeed[i]||defaultSpeed);
}
}
// Manual increment
$('input[name=increment]').each(function(i){
$(this).click(function(){
restart(i)();
increase(i)();
});
});
// Clear timer on "Clear"
$('input[name=clear]').each(function(i) {
$(this).click(clear(i));
});
// Restart timer on "Restart"
$('input[name=reset]').each(function(i) {
$(this).click(restart(i));
//Optionally, activate each timer:
increase(i)();
});
})();
这篇关于使用多个 setInterval 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!