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 script finished; the call stack is empty. Now โ and only now โ the event loop gets to pick what runs next.
5 / 9
Call stack
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 5 of 9
โ โ step ยท space play ยท 123 level