Skip to content

Instantly share code, notes, and snippets.

@pthrasher
Created July 13, 2012 15:26
Show Gist options
  • Save pthrasher/3105469 to your computer and use it in GitHub Desktop.
Save pthrasher/3105469 to your computer and use it in GitHub Desktop.
window.nextTick for the browser. ;-)
/*
* setTimeout(fn, 0) for realz, for modern browsers.
* AKA nextTick from node.
* Ripped from http://dbaron.org/log/20100309-faster-timeouts
* Most browsers don't actually let you specify timeouts of 0, so the below
* method is a better way of achieving this.
* Philip Thrasher, 2012
*/
(function(){
var timeouts = [],
messageName = 'nextTickPlz',
_nextTick = function(fn) {
timeouts.push(fn);
window.postMessage(messageName, "*");
},
_handleMessage(event) {
if (event != null && event.source === window && event.data === messageName) {
event.stopPropagation();
if (timeouts.length > 0) {
var fn = timeouts.shift();
fn();
}
}
};
window.addEventListener("message", handleMessage, true);
window.nextTick = _nextTick;
})();
@fatso83
Copy link

fatso83 commented May 25, 2023

This does not run:
you missed the function declaration for _handleMessage and handleMessage is not defined. Here's the fixed version:

(function(){

    var timeouts = [],
        messageName = 'nextTickPlz',

        _nextTick = function(fn) {
            timeouts.push(fn);
            window.postMessage(messageName, "*");
        },

        _handleMessage = function(event) {
            if (event != null && event.source === window && event.data === messageName) {
                event.stopPropagation();
                if (timeouts.length > 0) {
                    var fn = timeouts.shift();
                    fn();
                }
            }
        };

        window.addEventListener("message", _handleMessage, true);

        window.nextTick = _nextTick;
})();

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