1

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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.