Skip to content

Instantly share code, notes, and snippets.

@bluejava
Last active March 22, 2016 22:41
Show Gist options
  • Save bluejava/9415a075cd7810a267af to your computer and use it in GitHub Desktop.
Save bluejava/9415a075cd7810a267af to your computer and use it in GitHub Desktop.
A setTimeout replacement that pauses when browser window is not "visible"
/**
* This function uses the Page Visibility API to puase/restart the timeout such that
* the time you specify equates to "visibility time".
* Note: There is no clearTimeout capability - though it would not be hard to extend this to
* provide cancel-ability
*
* Usage:
* setVisiTimeout(function, ms, arg1, arg2, ... );
*
* LICENSE: Unlicense <http://unlicense.org/> / CC0
*/
function setVisiTimeout(fn,ms)
{
function now() { return new Date().getTime(); }
var started = now(); // record timestamp
// Convert the arguments into an array, excluding the first
// 2 arguments which are fn,ms - the remaining should be
// passed on to the fn.
var args = Array.prototype.slice.call(arguments,2);
// visibilitychange event callback
function vcEvent()
{
if(document.hidden) // clear timeout and sub out time passed
{
clearTimeout(to);
ms -= now() - started;
}
else // restart timeout with time left
{
to = setTimeout(timeup,ms);
started = now();
}
}
// Full time has been used up - call user function with args
function timeup()
{
if(document.removeEventListener)
document.removeEventListener("visibilitychange", vcEvent);
fn.apply(null, args);
}
// if not interrupted, this will trigger the timeup on its own
var to = setTimeout(timeup, ms);
// but if this event triggers, we'll have to do some bookkeeping
if(document.addEventListener)
document.addEventListener("visibilitychange", vcEvent);
}
@bluejava
Copy link
Author

Updated to support silly IE8.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment