Search code examples
javascriptbrowsertimertask-queueevent-loop

Why is this microtask executed before macrotask in event loop?


My understanding is that the full microtask task queue is processed after each macrotask.

If that is the case, why does the setTimeout callback get executed after the Promise microtasks in the following snippet of JavaScript?

console.log('start');

setTimeout(() => {
  console.log("setTimeout");
});

Promise.resolve().then(function() {
  console.log('promise');
});

console.log('end');

This outputs the following:

> "start"
> "end"
> "promise"
> "setTimeout"

Is it because of a ~4ms delay imposed by modern browsers?

From MDN:

In modern browsers, setTimeout()/setInterval() calls are throttled to a minimum of once every 4ms when successive calls are triggered due to callback nesting (where the nesting level is at least a certain depth), or after certain number of successive intervals.

Though this states that it is only true for successive callback nesting.


Solution

  • My understanding is that the full microtask task queue is processed after each macrotask.

    Yes. And the code that you ran, from console.log('start') to console.log('end'), is such a macrotask. After it ran to completion, the microtask queue with the promise callbacks is processed, and only after that the next macrotask (the timeout) gets to run.