clearInterval()不能正常使用javascript

时间:2015-12-31 11:59:46

标签: javascript

我有以下代码。这是我试图清除间隔,但它没有奏效。请帮助我。

$(document).ready(function(){
    var intervalId;
    $(window).focus(function(){
        var intervalId = setInterval(function(){
            console.log('working');
        }, 5000);
    });

    $(window).blur(function(){
        clearInterval(intervalId);
    });
});

1 个答案:

答案 0 :(得分:3)

请勿重新声明intervalId,然后它将成为focus函数的本地范围:

$(window).focus(function() {
    intervalId = setInterval(function() {
        console.log('working');
    }, 5000);
});

考虑这一部分:

$(document).ready(function() {
    var intervalId;
    $(window).focus(function() {
        // intervalId is not the same as the `window.intervalId`
        // The scope changes.
        var intervalId = setInterval(function() {
//------^^^---------- Remove this var.
        });
    });
});