I am reading a jQuery book and trying to do an example. In the example lightning flashes on the screen, and that part works fine. The problem is that when you switch tabs, and then switch back, the lightning starts flashing in rapid succession. The problem is supposed to be fixed using the window.onblur and window.onfocus events, but it's not working. Can anybody see what I am doing wrong?

There are three hidden lightning pictures with different id's, and three different functions that make each one flash. goLightning() sets the interval for each function to go, and stopLightning() should clear that interval. That part is what seems not to be working for all I know. Here is the code:

$(document).ready(function(){
    goLightning();
    window.onblur = stopLightning;
    window.onfocus = goLightning;
    var int1; var int2; var int3;

    // this function sets the lightning interval
    function goLightning() {
        int1 = setInterval(function() { lightning_one(); },4000);
        int2 = setInterval(function() { lightning_two(); },5000);
        int3 = setInterval(function() { lightning_three(); },7000);
     }

     // this function clears the lightning when the window isn't focused
     function stopLightning() {
        window.clearInterval(int1);
        window.clearInterval(int2);
        window.clearInterval(int3);
    }

    // these three functions make the lightning flash and seem to be working fine
    function lightning_one() {
            $("#container #lightning1").fadeIn(250).fadeOut(250);
    }
    function lightning_two() {
        $("#container #lightning2").fadeIn(250).fadeOut(250);
    }
    function lightning_three() {
        $("#container #lightning3").fadeIn(250).fadeOut(250);
    }
});

I have no idea why this isn't working. It seems like stopLightning() isn't clearing the interval, or window.onblur isn't working. Anyway, any feedback would be helpful. Thanks!

有帮助吗?

解决方案

Add stopLightning() to the beginning to goLightning(), before setting the new intervals.

其他提示

Re-arrange the following lines:

goLightning();
window.onblur = stopLightning;
window.onfocus = goLightning;
var int1; var int2; var int3;

in to this instead:

var int1, int2, int3, w = window;
w.onblur = stopLightning;
w.onfocus = goLightning;
goLightning();

Next, use the variable w instead of window in the stopLightning() function to ensure you use a reference to the proper window. Also, as @Kolink mentioned, it wouldn't hurt to put a call to stopLightning() at the beginning of your goLightning() function to ensure you don't have multiple instances running in the event the focus event gets fired more than once.

EDIT I moved the call to goLightning() after having set up the events - untested but I think it would be better that way?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top