Google Chrome actually runs on V8 which has a notion of a microtask queue. The postMessage
part is part of the DOM API and it schedules a microtask - similarly to what nextTick
does in node (although the chromium loop cycle is very different from Node's).
There is an old hack that uses postMessage to simulate a setTimeout(fn, 0)
that looks something like this:
var queue = [];
window.addEventListener("message", function(e){
if((e.source !== window) || (e.data === "flush")) return; // not the right message
queue.forEach(function(fn){ fn(); }); // call all functions;
queue = []; // clean the queue;
});
function nextTick(fn){
queue.push(fn); // add the function
window.postMessage(fn, "flush", "*");
}
There are clever tricks using MessageChannel
instead of the window directly but it's all the same idea.
You can find old mentions of this technique in this blog post it is rarely used anymore since there is a faster hack for a faster setTimeout using mutation observers.
Here is a relatively modern source on different techniques.
setTimeout(fn, 0)
usingpostMessage
by posting a message to yourself - it gets dispatched asynchronously but without the overhead of the timers queue. Note that it is no longer used and typically aMutationObserver
hack is used instead.