Skip to content

Instantly share code, notes, and snippets.

@taufik-nurrohman
Forked from Yaffle/gist:1900579
Last active December 23, 2015 02:59
Show Gist options
  • Save taufik-nurrohman/6570776 to your computer and use it in GitHub Desktop.
Save taufik-nurrohman/6570776 to your computer and use it in GitHub Desktop.
function setVisibleTimeout(callback, delay) {
var id = null,
t = 0,
prefix = '';
'o webkit moz ms'.replace(/\S+/g, function(p) {
if ((p + 'Hidden') in document) {
prefix = p;
}
});
function onVisibilityChange(event) {
var now = +new Date(); // event.timeStamp is buggy in FF 10 (in microseconds)
if (document[prefix ? prefix + 'Hidden' : 'hidden']) {
if (id !== null) {
delay = Math.max(0, delay - Math.max(0, now - t)); // defense from now < t if clock jump occured
clearTimeout(id);
id = null;
}
} else {
if (id === null) {
t = now;
id = setTimeout(function() {
id = null;
document.removeEventListener(prefix + 'visibilitychange', onVisibilityChange, false);
setTimeout(callback, 0);
}, delay);
}
}
}
document.addEventListener(prefix + 'visibilitychange', onVisibilityChange, false);
onVisibilityChange({timeStamp: +new Date()});
return (function () {
document.removeEventListener(prefix + 'visibilitychange', onVisibilityChange, false);
if (id !== null) {
clearTimeout(id);
id = null;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment