Вопрос

I have a small notification & alert system.

I'm just trying to detect if the window's state is blur or focus and then listing these alerts and notifications. But my clearInterval method doesn't work. Here is the code;

$(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);
    });
});

The console.log() output for these clearInterval is undefined.

Это было полезно?

Решение 2

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

})

Those var declarations make these two variables local to the function, and your code will not overwrite the variables in the ready-handler's scope. Therefore, the values will be lost and the intervals are not cleared. Just omit "var".

Другие советы

It may be because you are using the wrong (out of scope) intervalStoryAlerts and intervalMessageAlerts, so they point at new intervals. Instead drop the re-declaration in the bind for the focus. Try:

// 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); 
})
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top