When using setInterval, if I switch tabs in Chrome and go back, the slider goes crazy catching up

How to detect when a tab is focused or not in Chrome with Javascript?

window.addEventListener('focus', function() {
    document.title="focused";
},false);

window.addEventListener('blur', function() {
    document.title="not focused";
},false);

To apply to your situation:

var autopager;
function startAutopager() {
    autopager = window.setInterval(nextImage, 8000);
}
function stopAutopager() {
    window.clearInterval(autopager);
}

window.addEventListener('focus', startAutopager);    
window.addEventListener('blur', stopAutopager);

Note that in the latest version of Chromium, there is either a bug or a ‘feature’ which is making this less reliable, requiring that the user has clicked at least once anywhere in the window. See linked question above for details.

Leave a Comment