为什么 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()输出是未定义的。

这可能是因为您使用了错误的(超出范围)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); 
})
….bind("focus", function(event){
   // […]
   var intervalStoryAlerts = setInterval(loadStoryAlerts, 6000);
   var intervalMessageAlerts = setInterval(loadMessageAlerts, 16000); 
})

那些var声明使这两个变量局部函数,你的代码将不会覆盖在现成的处理程序的范围内的变量。因此,这些值将会丢失,间隔也不会被清除。省略" var "

最新更新