我有一个定时器功能,我想清除超时或重置该功能,因为每次我执行它时,都会创建一个新的超时,所以我收到了几个计数。 我的想法是每次执行该功能时都重置计数。我只想要 1 个计时器实例并获得正确的计数。如果执行几次我想重启到0的功能。
这是我的代码:
var timeouts = new Array();
var timer = null;
io.sockets.on('connection', function (client)
{
client.on("start", function (){
console.log('Someone has pressed Start button',new Date().getTime());
//try to kill all timeouts
for (var timeout in timeouts) {
clearTimeout(timeout);
};
if(this.timer == null) {
this.timer = new timer(1000, function (data) {
io.sockets.emit('timeupdate', data);
})
}else {
this.timer = null;
});
});
function timer(delay, callback)
{
// self-reference
var self = this;
if (!(this instanceof timer)) {
return new timer();
}
// attributes
var counter = 0;
var start = new Date().getTime();
/**
* Delayed running of the callback.
*/
function delayed()
{
console.log(counter);
callback(counter);
counter ++;
var diff = (new Date().getTime() - start) - counter * delay;
var timeOut = setTimeout(delayed, delay - diff);
timeouts.push(timeOut);
}
// start timer
delayed();
var timeout = setTimeout(delayed, delay);
timeouts.push(timeout);
}
提前谢谢你。
最佳答案
使用 clearTimeout()
是正确的方法。问题是您的 for
循环。这可能看起来像经典的 foreach
循环,但事实并非如此。你必须做:
for (var i=0; i< timeouts.length; i++) {
clearTimeout(timeouts[i]);
}
或者,我个人也不喜欢这样:
for (var i in timeouts) {
clearTimeout(timeouts[i]); // note how the array is indexed using var i
}
这是一个常见的 JavaScript 陷阱 - for (x in y)
循环实际上遍历数组的索引,而不是值。它还可以遍历对象的属性。试试看:
var a = [3, 2, 5, 8];
for (var i in a) {
console.log(i);
console.log(a[i]);
}
var o = { test: 'hello', number: 1234 };
for (var x in o)
console.log(x);
关于javascript - 清除 setTimeout 或 reset 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14254799/