Skip to content Skip to sidebar Skip to footer

Pausing Setinterval When Page/ Browser Is Out Of Focus

I have a simple slideshow that I've made on a client's homepage, using setInterval to time the rotations. To prevent browsers from screwing up setInterval when the page isn't in fo

Solution 1:

Immediately inside setInterval, place a check to see if the document is focused. The interval will continue firing as usual, but the code inside will only execute if the document is focused. If the window is blurred and later refocused, the interval will have continued keeping time but document.hasFocus() was false during that time, so there's no need for the browser to "catch up" by executing the code block a bunch of times when focus is restored.

var timePerInterval = 7000;
$(document).ready(function() {
    setInterval(function(){
        if ( document.hasFocus() ) {
            // code to be run every 7 seconds, but only when tab is focused
        }
    }, timePerInterval );
});

Solution 2:

Try something like this:

var myInterval;
var interval_delay = 500;
var is_interval_running = false; //Optional

$(document).ready(function () {
    $(window).focus(function () {
        clearInterval(myInterval); // Clearing interval if for some reason it has not been cleared yetif  (!is_interval_running) //Optional
            myInterval = setInterval(interval_function, interval_delay);
    }).blur(function () {
        clearInterval(myInterval); // Clearing interval on window blur
        is_interval_running = false; //Optional
    });
});

interval_function = function () {
     is_interval_running = true; //Optional// Code running while window is in focus
}

Some testing done in IE9 and FF6

Post a Comment for "Pausing Setinterval When Page/ Browser Is Out Of Focus"