Is there a way to stop setTimeout("myfunction()",10000);
from counting up when the page isn't active. For instance,
myfunction()
doesn't fire until they've come back for another 8000ms.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.
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.
Working with asynchronous functionssetTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack.
(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:
document.hidden
to detect when the page is not visible.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With