-2

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

我只是想检测窗口的状态是模糊还是焦点,然后列出这些警报和通知。但是我的 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() 输出是未定义的。

4

2 回答 2

2

可能是因为您使用了错误的(超出范围)intervalStoryAlertsand intervalMessageAlerts,所以它们指向新的间隔。而是将重新声明放在焦点的绑定中。尝试:

// 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); 
})
于 2013-01-13T21:56:56.127 回答
1
….bind("focus", function(event){
   // […]
   var intervalStoryAlerts = setInterval(loadStoryAlerts, 6000);
   var intervalMessageAlerts = setInterval(loadMessageAlerts, 16000); 

})

这些var声明使这两个变量成为函数的局部变量,并且您的代码不会覆盖就绪处理程序范围内的变量。因此,值将丢失并且间隔不会被清除。只需省略“ var”。

于 2013-01-13T22:32:24.650 回答