Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Jul 28, 2014

awesome!

@wesleytodd

This comment has been minimized.

Copy link

commented Oct 21, 2014

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
You can’t perform that action at this time.