-
-
Save taufik-nurrohman/6570776 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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