3

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

先感谢您。

4

1 回答 1

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)loop 实际上迭代数组的索引,而不是值。它还可以迭代对象的属性。试试看:

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);
于 2013-01-10T09:51:35.363 回答