Skip to content

Instantly share code, notes, and snippets.

@kane-thornwyrd
Created January 12, 2015 09:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kane-thornwyrd/13c8d37f041bc77bfa06 to your computer and use it in GitHub Desktop.
Save kane-thornwyrd/13c8d37f041bc77bfa06 to your computer and use it in GitHub Desktop.
// Only add setZeroTimeout to the window object, and hide everything
// else in a closure.
(function() {
var timeouts = [];
var messageName = "zero-timeout-message";
// Like setTimeout, but only takes a function argument. There's
// no time argument (always zero) and no arguments (you have to
// use a closure).
function setZeroTimeout(fn) {
timeouts.push(fn);
window.postMessage(messageName, "*");
}
function handleMessage(event) {
if (event.source == window && event.data == messageName) {
event.stopPropagation();
if (timeouts.length > 0) {
var fn = timeouts.shift();
fn();
}
}
}
window.addEventListener("message", handleMessage, true);
// Add the one thing we want added to the window object.
window.setZeroTimeout = setZeroTimeout;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment