Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who is first between macrotask and microtask in javascript?

I'm confused which task is taken first by event loop.

The reason is like below.

Stackoverflow answer from this

After this macrotask has finished, all available microtasks will be processed

Similar example from this blog article

setTimeout(() => console.log('Macro task'), 0);
Promise.resolve().then(() => console.log('Micro task'));

So, it is very confusing for me. What I understood till now is this.

  1. Code that is not callback function is inserted into call stack right away.
  2. Callback function of setTimeout() is inserted into Macro Task Queue.
  3. Callback function of Promise is inserted into Micro Task Queue.
  4. When call stack is empty, event loop takes task from Micro Task Queue and runs.
  5. After execution of all micro tasks, event loop takes task from Macro Task Queue and runs.

This process is my understanding and am I right?

like image 797
undefined Avatar asked May 13 '26 09:05

undefined


2 Answers

Micro-task queue is checked right after the script finishes, I think. It is before the checking of macro-task queue.

See here for detailed information.

like image 196
Jim Jin Avatar answered May 15 '26 01:05

Jim Jin


Because the script itself is treated as a macrotask so that at the end the enqueued microtasks are executed.

So the promise is a microtask, setTimeout callback is a macrotask, but the script is a macrotask as well.

As a result, script -> promise -> setTimeout

More details here: https://medium.com/javascript-in-plain-english/javascript-event-loop-y-promises-951ba6845899

like image 30
Tan Dat Avatar answered May 15 '26 01:05

Tan Dat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!