Created
January 6, 2012 19:31
-
-
Save briancavalier/1572025 to your computer and use it in GitHub Desktop.
Enqueue a task for nextTick in many environments
This file contains hidden or 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
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