3

I've heard that postMessage is Google Chrome's implementation of nextTick. I'm a little confused by this statement since I thought that postMessage was used to communicate between web workers.

I've tried expressions like postMessage(function() {return;});, and that only errs instead of scheduling a function to be run when the event loop is idle. It seems that postMessage only takes a message as expected.

How can postMessage be used as means of scheduling function calls when the event loop is idle?

2
  • 1
    There is an old hack that produces a faster setTimeout(fn, 0) using postMessage 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 a MutationObserver hack is used instead. Commented Jan 5, 2015 at 21:31
  • 1
    Here - some reading material: dbaron.org/log/20100309-faster-timeouts Commented Jan 5, 2015 at 21:33

1 Answer 1

6

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.

2
  • window.postMessage(fn, "flush", "*"); is there a typo? Why pass fn to possmessage?
    – Littlee
    Commented Jan 14, 2021 at 4:07
  • postMessage ain't the microtask this is a task that queued in the post message task queue
    – MaximPro
    Commented Jun 11, 2022 at 7:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.