Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run setTimeout only when tab is active

Tags:

Is there a way to stop setTimeout("myfunction()",10000); from counting up when the page isn't active. For instance,

  1. A user arrives at a "some page" and stays there for 2000ms
  2. User goes to another tab, leaves "some page" open.
  3. myfunction() doesn't fire until they've come back for another 8000ms.
like image 712
Kyle Cureau Avatar asked Apr 23 '11 19:04

Kyle Cureau


People also ask

Does setInterval run in inactive tab?

The script overrides setInterval , setTimeout , and other methods to make sure they run in the background which, in turn, will prevent them from getting throttled when the tab becomes inactive. Setting it up is pretty straightforward. All you need to do is copy HackTimer.

How do I run setTimeout multiple times?

If you need to run a function multiple times, use the setInterval() method. To stop the timeout and prevent the function from executing, use the clearTimeout() method. The JavaScript setTimeout() method returns an ID which can be used in clearTimeout() method.

Does setTimeout work asynchronous?

Working with asynchronous functionssetTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack.


2 Answers

(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.
like image 190
Šime Vidas Avatar answered Oct 25 '22 16:10

Šime Vidas


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.

like image 40
Jasuten Avatar answered Oct 25 '22 17:10

Jasuten