JavaScript - On browsers tab switching Interval doesn't get cleared with clearInterval & window.onfocus/blur get called twice

StackOverflow https://stackoverflow.com/questions/14299963

  •  15-01-2022
  •  | 
  •  

Question

I've got a simple script that fades in and out some images. It works perfectly fine, before I switch to another tab and then switch back. After switching back seems like interval that runs animation, doesn't get cleared and function keeps running.

The real code:

var img0 = document.getElementById("image0");
var img1 = document.getElementById("image1");
var img2 = document.getElementById("image2");

var imgs = [img0,img1,img2];

var intervalFading;
var intervalAnimate;

var imgThis = 0;
var imgNext = 1;

var fadeIn = 0;
var fadeOut = 1;

var start;



function animateFading() {
    fadeIn+=0.1;
    fadeOut-=0.1;
    imgs[imgThis].style.opacity = fadeOut;
    imgs[imgNext].style.opacity = fadeIn;

if (fadeIn >= 1) {
    clearInterval(intervalAnimate);

    if (imgNext < 2) {
        imgNext++;
    } else {
        imgNext = 0;
    }

    if (imgThis < 2) {
        imgThis++;
    } else {
        imgThis = 0;
    }

    fadeIn = 0;
    fadeOut = 1;
}

}

function fading() {
intervalAnimate = setInterval(animateFading,50);
}

function startFading() {
start = setInterval(fading, 3000);
}


window.addEventListener('load', startFading);

So I came up with following solution:

function startFading() {
start = setInterval(fading, 3000);
}

function stopFading() {

    console.log("stop");
    clearInterval(start);
}


window.addEventListener('focus', startFading);    
window.addEventListener('blur', stopFading);

And that fixes the problem. But for FF only. In FF the script runs just perfect. In Chrome window.onfocus gets called twice! Why twice?

Please help to fix either first problem in a different way or second with Chrome. thx!

Was it helpful?

Solution

This appears to be a known chromium bug:

http://code.google.com/p/chromium/issues/detail?id=117307

Possible solutions are:

  1. f you're using jQuery, you can try using $.on('focus', startFading)
  2. you can set a boolean and make sure startFading doesn't get called more than once:

Example:

var startedFading = false;

function startFading() {
    if (!startedFading) {
        startedFading = true;
        start = setInterval(fading, 3000);
    }
}

function stopFading() {
    startedFading = false;
    console.log("stop");
    clearInterval(start);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top