Skip to content

Instantly share code, notes, and snippets.

@timnew
Created June 23, 2014 07:23
Show Gist options
  • Save timnew/645026c53e8f9ce7df44 to your computer and use it in GitHub Desktop.
Save timnew/645026c53e8f9ce7df44 to your computer and use it in GitHub Desktop.
process.nextTick
process.nextTick = (function () {
var canSetImmediate = typeof window !== 'undefined'
&& window.setImmediate;
var canPost = typeof window !== 'undefined'
&& window.postMessage && window.addEventListener;
if (canSetImmediate) {
return function (f) { return window.setImmediate(f) };
}
if (canPost) {
var queue = [];
window.addEventListener('message', function (ev) {
var source = ev.source;
if ((source === window || source === null) && ev.data === 'process-tick') {
ev.stopPropagation();
if (queue.length > 0) {
var fn = queue.shift();
fn();
}
}
}, true);
return function nextTick(fn) {
queue.push(fn);
window.postMessage('process-tick', '*');
};
}
return function nextTick(fn) {
setTimeout(fn, 0);
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment