为什么clearInterval在窗口模糊和焦点事件功能中不起作用?

时间:2013-01-13 21:54:21

标签: javascript jquery clearinterval

我有一个小通知&警报系统。

我只是想检测窗口的状态是模糊还是焦点,然后列出这些警报和通知。但我的clearInterval方法不起作用。这是代码;

$(document).ready(function(){
     setTimeout(function(){loadMessageNotifications()},600);
     setTimeout(function(){loadStoryNotifications()},400);

       var intervalStoryAlerts = setInterval(function(){loadStoryAlerts()},6000);
       var intervalMessageAlerts = setInterval(function(){loadMessageAlerts()},16000); 

    $(window).bind("focus", function(event){

         setTimeout(function(){loadMessageNotifications()},600);
         setTimeout(function(){loadStoryNotifications()},400);

       var intervalStoryAlerts = setInterval(function(){loadStoryAlerts()},6000);
       var intervalMessageAlerts = setInterval(function(){loadMessageAlerts()},16000); 

    }).bind("blur", function(event){

        clearInterval(intervalStoryAlerts);
        clearInterval(intervalMessageAlerts);
    });
});

这些clearInterval的console.log()输出未定义。

2 个答案:

答案 0 :(得分:2)

可能是因为您使用了错误的(超出范围)intervalStoryAlertsintervalMessageAlerts,因此他们指向新的时间间隔。而是在焦点的绑定中删除重新声明。尝试:

// variables defined in enclosing scope
var intervalStoryAlerts = ..;
var intervalMessageAlerts = ..;

$(window).bind("focus", function(event){

     setTimeout(function(){loadMessageNotifications()},600);
     setTimeout(function(){loadStoryNotifications()},400);

     // remove var here so that new variables are not created
     intervalStoryAlerts = setInterval(function(){loadStoryAlerts()},6000);
     intervalMessageAlerts = setInterval(function(){loadMessageAlerts()},16000); 
})

答案 1 :(得分:1)

….bind("focus", function(event){
   // […]
   var intervalStoryAlerts = setInterval(loadStoryAlerts, 6000);
   var intervalMessageAlerts = setInterval(loadMessageAlerts, 16000); 

})

那些var declarations使这两个变量成为函数的本地变量,并且你的代码不会覆盖ready-handler范围内的变量。因此,值将丢失并且不会清除间隔。只需省略“var”。