Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
nextTick implementation for the browser
// nextTick - by stagas / public domain
var nextTick = (function () {
var queue = [];
var dirty = false;
var fn;
var hasPostMessage = !!window.postMessage;
var messageName = 'nexttick';
var trigger = (function () {
return hasPostMessage
? function trigger () {
window.postMessage(messageName, '*');
}
: function trigger () {
setTimeout(function () { processQueue() }, 0);
};
}());
var processQueue = (function () {
return hasPostMessage
? function processQueue (event) {
if (event.source === window && event.data === messageName) {
event.stopPropagation();
flushQueue();
}
}
: flushQueue;
})();
function flushQueue () {
while (fn = queue.shift()) {
fn();
}
dirty = false;
}
function nextTick (fn) {
queue.push(fn);
if (dirty) return;
dirty = true;
trigger();
}
if (hasPostMessage) window.addEventListener('message', processQueue, true);
nextTick.removeListener = function () {
window.removeEventListener('message', processQueue, true);
}
return nextTick;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.