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 that interval that runs animation doesn't get cleared and animateFading function keeps running.

Why is it happening, how does tab switching affects script? And how could I make it work properly? thx!

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);

Solution:

var startedFading = false;

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

function stopFading() {
    startedFading = false;
        clearInterval(startFading);
}


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

The boolean is for Chrome, as it fires twice

window.addEventListener('focus', startFading);

&

window.addEventListener('blur', stopFading);
Was it helpful?

Solution

Most browsers have a feature that redirects the memory usage capacity to the only active tab (currently being viewed). Thus, the setInterval and setTimeout timings are affected when you switch the current tab (if you're using Google Chrome, you can see the memory usage of each tab by pressing Shift+Esc. The current tab will use up to 25%, whereas the rest don't pass of the 5%)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top