Skip to content

Instantly share code, notes, and snippets.

@espretto
Last active October 24, 2016 22:37
Show Gist options
  • Save espretto/ec79d6d0fc7a898b92b1 to your computer and use it in GitHub Desktop.
Save espretto/ec79d6d0fc7a898b92b1 to your computer and use it in GitHub Desktop.
progressive shim to defer execution until next run-loop cycle
/**
* progressive shim to defer execution until next run-loop cycle
*
* prefers
* - `process.nextTick` over
* - `process.setImmediate` or `window.setImmediate` over
* - `window.requestAnimationFrame` over
* - `window.postMessage` and `window.addEventListener` over
* - `setTimeout` as the very last resort
*/
ns = {};
ns.nextTick = (function (root) {
"use strict";
var owner = typeof process === "undefined" ? root : process,
vendorPrefixes = "webkitR-mozR-msR-oR-r".split("-"),
suffix = "equestAnimationFrame",
nextTick = owner.nextTick || owner.setImmediate,
queue;
while (!nextTick && vendorPrefixes.length){
nextTick = owner[vendorPrefixes.pop() + suffix];
}
if (!nextTick && root.postMessage && root.addEventListener){
queue = [];
root.addEventListener('message', function(evt){
var source = evt.source;
if ((source == root || source == null) && evt.data === 'nextTick'){
evt.stopPropagation();
if (queue.length) queue.shift()();
}
}, true);
return function(func){
queue.push(func);
root.postMessage('nextTick', '*');
};
}
nextTick = nextTick || setTimeout;
return function (){
return nextTick.apply(owner, arguments);
};
}(this));
/**
* minified version ~0.5kb:
nextTick=function(c){for(var b="undefined"===typeof process?c:process,e=["webkitR","mozR","msR","oR","r"],a=b.a||b.setImmediate,d;!a&&e.length;)a=b[e.pop()+"equestAnimationFrame"];!a&&c.postMessage&&c.addEventListener&&(d=[],c.addEventListener("message",function(a){var b=a.source;b!=c&&null!=b||"nextTick"!==a.data||(a.stopPropagation(),d.length&&d.shift()())},!0),a=function(a){d.push(a);c.postMessage("nextTick","_")});a=a||setTimeout;return function(){return a.apply(b,arguments)}}(this);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment