Run setTimeout only when tab is active

You can do something like:

$([window, document]).blur(function() {
  // Clear timeout here
}).focus(function() {
  // start timeout back up here
});

Window is for IE, document is for the rest of the browser world.


Great answer by Šime Vidas, it helped me with my own coding. For completeness sake I made an example for if you want to use setTimeout instead of setInterval:

(function() {

    function myFunction() {
        if(window.blurred) {
            setTimeout(myFunction, 100);
            return;
        }

        // What you normally want to happen

        setTimeout(myFunction, 10000);
    };
    setTimeout(myFunction, 10000);

    window.onblur = function() {window.blurred = true;};
    window.onfocus = function() {window.blurred = false;};

})();

You'll see that the window blurred check has a shorter time set than normal, so you can set this depending on how soon you require the rest of the function to be run when the window regains focus.


(function() {
  var time = 10000,
      delta = 100,
      tid;

  tid = setInterval(function() {
    if ( document.hidden ) { return; }    
    time -= delta;
    if ( time <= 0 ) {
      clearInterval(tid);
      myFunction(); // time passed - do your work
    }        
  }, delta);
})();

Live demo: https://jsbin.com/xaxodaw/quiet


Changelog:

  • June 9, 2019: I’ve switched to using document.hidden to detect when the page is not visible.

I use almost the same approach as Šime Vidas in my slider but my code is based on document.visibilityState for page visibility checking:

document.addEventListener("visibilitychange", () => {

  if ( document.visibilityState === "visible" ) {

    slideshow.play();

  } else {

    slideshow.pause();
  }
});
  • About Page Visibility API: https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API