Javascript间隔未清除

Sup*_*erq 0 html javascript browser jquery

我有一个相当复杂的页面,有很多ajax调用和后续的dom操作.在一个特定的调用中,它设置一个具有时间限制的间隔(基本上是一个计时器).我已经在clearInterval()任何地方设置,甚至在功能中,但在非常特殊的用例中(它很复杂,我无法确定重现缺陷的确切原因和步骤).

$(function() {
  window.timer_interval; 
  // ...
})
function timer()
{
    var current = 0; 
    time_limit = 60;                                
    window.timer_interval = setInterval(function() {
        minute = ( "0" +  Math.round(Math.floor((time_limit - current)/60))).slice(-2); 
        seconds = ("0" + ((time_limit - current)%60)).slice(-2); 

        $('#timer').html(minute + ":" + seconds);

        if (current >= time_limit) {
            clearInterval(window.timer_interval); 
            window.timer_interval = false; 
        }
        current = current + 1; 
    }, 1000);
}
Run Code Online (Sandbox Code Playgroud)

我已经使用了firbug来检测它的值window.timer_interval,它是false甚至条件都满足.一件事可能是一些图像传输失败(这是可能的应用程序行为,代码写入优雅地降级).我在Mozilla开发.

Dan*_*nez 7

我的猜测是你正在设置间隔,然后再次设置间隔而不先清除它,这样之前设置的内容将永远运行.

如果我正确添加检查以清除之前的间隔setInterval将纠正问题.我已经为下面的代码创建了一个函数,当你打电话时会发生这个函数setInterval.

// starts an interval function, making sure to cancel one that is previously running
function startSharedInterval(func) {
    if (window.timer_interval) {
        clearInterval(window.intervalID);
        window.timer_interval = 0;
    }

    window.timer_interval = setInterval(func, 1000);
};

// ... in timer() 
startSharedInterval(function () {
    minute = ( "0" +  Math.round(Math.floor((time_limit - current)/60))).slice(-2)  ; 
    // ... rest of code
});
Run Code Online (Sandbox Code Playgroud)

如果您只有一个计时器,那么您可以避免使用全局范围并利用闭包使计时器始终清除.

在下面的代码中,interval_id在父timer()函数中创建.这将在内部匿名函数中可用,以便在60之后的执行完成时清除.您可以通过这种方式同时运行多个实例.

function timer() {

    var current = 0;
    var time_limit = 60;
    var interval_id = setInterval(function () {

        minute = ("0" + Math.round(Math.floor((time_limit - current) / 60))).slice(-2);
        seconds = ("0" + ((time_limit - current) % 60)).slice(-2);

        $('#timer').html(minute + ":" + seconds);

        if (current >= time_limit) {
            clearInterval(interval_id);
        }
        current = current + 1;
    }, 1000);
}
Run Code Online (Sandbox Code Playgroud)