Skip to content

Instantly share code, notes, and snippets.

@briancavalier
Created January 6, 2012 19:31
Show Gist options
  • Save briancavalier/1572025 to your computer and use it in GitHub Desktop.
Save briancavalier/1572025 to your computer and use it in GitHub Desktop.
Enqueue a task for nextTick in many environments
soon = (function() {
var enqueueTask;
if(typeof process != 'undefined' && typeof process.nextTick == 'function') {
// Node nextTick
enqueueTask = process.nextTick;
} else if (typeof setImmediate == 'function') {
// setImmediate for new IE
enqueueTask = setImmediate;
} else if (typeof MessageChannel != 'undefined') {
// modern browsers
// http://www.nonblocking.io/2011/06/windownexttick.html
var channel, head, tail;
channel = new MessageChannel();
// task list
head = {};
tail = head;
channel.port1.onmessage = function () {
var next = head.next;
var task = next.task;
head = next;
task();
};
enqueueTask = function (task) {
tail = tail.next = {task: task};
channel.port2.postMessage();
};
} else {
// Fallback to setTimeout
enqueueTask = function(func) {
setTimeout(func, 0);
}
}
return enqueueTask;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment