Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Show comment
Hide comment
@bluejava

bluejava Aug 21, 2015

Updated to support silly IE8.

Owner

bluejava commented Aug 21, 2015

Updated to support silly IE8.

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