J Seabolt
J Seabolt

Reputation: 2998

Why does setTimeout occur after Promise.resolve()

In the event loop there are:

  1. Phases of the event loop, each containing their own callback queue
  2. Microtask queue, which includes resolved promise callbacks

As I understand it, the microtask queue runs after every phase of the event loop.

The first phase of the event loop is the "timers" phase. See here: https://blog.insiderattack.net/event-loop-and-the-big-picture-nodejs-event-loop-part-1-1cb67a182810

enter image description here

So given this code:

setTimeout(() => console.log('TIMEOUT')); 
Promise.resolve().then(() => console.log('PROMISE'); 

I would expect the logs to read

TIMEOUT
PROMISE

But instead you get

PROMISE
TIMEOUT

I understand that the "PROMISE" log is from a callback in the microtask queue. But the timer phase is the first phase. If in each phase we first run the callback queue and THEN the microtask queue, why am I seeing the timer log after the log in the microtask queue?

Upvotes: 0

Views: 88

Answers (2)

Sandeep M
Sandeep M

Reputation: 350

setTimeout always runs after the execution of current script. So even if your Promise and setTimeout has a resolve time of 1s, the promise will be resolved first and only after that, the timeout will be triggered.

Js info

Upvotes: 0

Kaiido
Kaiido

Reputation: 137084

Because your code is ran from a task, and that after this initial task, there will already be a microtask checkpoint, just like after every task.

It's not very clear in the diagram, but even if you had 33 timer callbacks firing in the same phase, they would all empty the nextTick queue and the microtask queue, so there would have been like 33 such checkpoints.

Upvotes: 0

Related Questions