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!