Created
September 18, 2011 18:59
-
-
Save stagas/1225404 to your computer and use it in GitHub Desktop.
nextTick implementation for the browser
This file contains 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
// 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