3

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?

saketh
  • 803
  • 1
  • 10
  • 24
undefined
  • 978
  • 1
  • 12
  • 30

2 Answers2

2

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.

Jim Jin
  • 1,249
  • 1
  • 15
  • 28
2

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

Tan Dat
  • 2,888
  • 1
  • 17
  • 39