清除setTimeout或重置功能

时间:2013-01-10 09:43:48

标签: javascript node.js timer settimeout

我有一个计时器功能,我想清除超时或重置功能,因为每次执行它时,都会创建一个新的超时,所以我收到了几个计数。 我的想法是每次执行函数时重置计数。我只需要1个计时器实例并获得正确的计数。如果if多次执行我要重启的函数为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);
}

提前谢谢。

1 个答案:

答案 0 :(得分:2)

使用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);