我正在使用下面的简单倒计时,除非将它放在循环中,否则它正常工作。在循环期间,前一个和新的计数器都保持工作。我想杀死前一个计数器并以新的开始,这是我无法实现的。请有人帮忙吗
function triggerEvery60Sec(){
var myCounter = new Countdown({
seconds:5, // number of seconds to count down
onUpdateStatus: function(sec){console.log(sec);}, // callback for each second
onCounterEnd: function(){ alert('counter ended!');} // final action
});
myCounter.start();
}
function Countdown(options) {
var timer,
instance = this,
seconds = options.seconds || 10,
updateStatus = options.onUpdateStatus || function () {},
counterEnd = options.onCounterEnd || function () {};
function decrementCounter() {
updateStatus(seconds);
if (seconds === 0) {
counterEnd();
instance.stop();
}
seconds--;
}
this.start = function () {
clearInterval(timer);
timer = 0;
seconds = options.seconds;
timer = setInterval(decrementCounter, 1000);
};
this.stop = function () {
clearInterval(timer);
};
}
答案 0 :(得分:0)
不是在循环中声明你的变量,也许你应该在之前声明它,并在你的循环中操纵它。
var myCounter = null;
function triggerEvery60Sec(){
myCounter = new Countdown({
seconds:5, // number of seconds to count down
onUpdateStatus: function(sec){console.log(sec);}, // callback for each second
onCounterEnd: function(){ alert('counter ended!');} // final action
});
myCounter.start();
}