Promise vs setTimeout โ€” interactive event loop example

1console.log('start');
2
3setTimeout(() => {
4 console.log('timeout');
5}, 0);
6
7Promise.resolve().then(() => {
8 console.log('promise');
9});
10
11console.log('end');

The 0ms timer already expired, so the timeout callback enters the task queue โ€” where it must wait, because the stack is still busy. Meanwhile console.log("end") runs.

4 / 9

Call stack

script

Web APIs โ€” browser land

The event loop โ€” is the call stack empty? โ†’ drain the microtask queue first โ†’ then take one callback.

Microtask queue โ€” priority

promise cb

Callback queue

timeout cb

Console

01start
02end

Fig. โ€” Promise vs setTimeout ยท step 4 of 9

โ† โ†’ step ยท space play ยท 123 level