Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Created June 19, 2012 10:57
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save WebReflection/2953527 to your computer and use it in GitHub Desktop.
Save WebReflection/2953527 to your computer and use it in GitHub Desktop.
process.nextTick(callback) for browsers too
!function (window) {"use strict";
// by WebReflection - WTFPL License
var
prefixes = "r webkitR mozR msR oR".split(" "),
process = "process",
nextTick = "nextTick",
i = 0,
p = window[process] || (window[process] = {})
;
while (!p[nextTick] && i < prefixes.length)
p[nextTick] = window[prefixes[i++] + "equestAnimationFrame"]
;
p[nextTick] || (p[nextTick] = window.setImmediate || window.setTimeout);
}(this);
@mdunisch
Copy link

awesome!

@wesleytodd
Copy link

Thanks for this, but I had a few problems with it.

First, adding any of the window functions onto process causes an illegal invocation, at least in chrome. To fix this you have to bind it back to the window. My version uses bind so is probably not backwards compatible, but works for me.

Second a note on using this as a way to minify for window. If you use a build tool like browserify to wrap this it will break because it wraps everything in a closure.

To fix that issue while still remaining small I made a few modifications:

(function(window, nextTick, process, prefixes, i, p, fnc) {
    p = window[process] || (window[process] = {});
    while (!fnc && i < prefixes.length) {
        fnc = window[prefixes[i++] + 'equestAnimationFrame'];
    }
    p[nextTick] = p[nextTick] || (fnc && fnc.bind(window)) || window.setImmediate || window.setTimeout;
})(window, 'nextTick', 'process', 'r webkitR mozR msR oR'.split(' '), 0);

With the additional bind fix and changing this to window the original is 245 bytes. This one with both fixes is 219 bytes. I tested both with this script and they seemed to work:

console.log('Before', Date.now());
process.nextTick(function(){
    console.log('During', Date.now());
});
console.log('After', Date.now());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment