1

清除间隔后,我很难将时间重新启动到 10 秒。当状态为成功时,它应该再次运行设置的间隔

下面是我的代码:

<code>
var countdown = 10;
var startTime = currTimer();
var myInterval = setInterval(function() {
countdown--;
if(countdown == 0){
    var endTime = currTimer();
    clearInterval(myInterval);
    countdown = 10;

    if (status == "success"){
        setTimeout(function(){myInterval}, 200); 
    }

}

io.sockets.emit('timer', { countdown: countdown });
}, 2000);
</code>
4

1 回答 1

1

最好的方法可能是将函数保存在可以传递给setInterval调用的变量中。这样它就变成了一条单一的、容易重复的线。

var countdown = 10;
var startTime = currTimer();
var onInterval = function() {
    countdown--;
    if(countdown == 0){
        var endTime = currTimer();
        clearInterval(myInterval);
        countdown = 10;

        if (status == "success"){
            setTimeout(function(){
                myInterval = setInterval(onInterval, 2000);
            }, 200); 
        }

    }

    io.sockets.emit('timer', { countdown: countdown });
};
var myInterval = setInterval(onInterval, 2000);
于 2013-11-12T09:48:11.407 回答