Skip to content

Instantly share code, notes, and snippets.

Last active Mar 22, 2016
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 <> / 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 =,2);
// visibilitychange event callback
function vcEvent()
if(document.hidden) // clear timeout and sub out time passed
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()
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
document.addEventListener("visibilitychange", vcEvent);
Copy link

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