The Event Loop
Why does a 0 ms timer print last? Follow the call stack, the promise queue and the timer queue.
JavaScript · beginner · 7 min · 8 steps · free
What you'll learn
- Explain that callbacks wait for the call stack to empty
- Order sync code, promise callbacks and timers
EventLoop.js
console.log('1: start');
setTimeout(() => {
console.log('4: timer');
}, 0);
Promise.resolve().then(() => {
console.log('3: promise');
});
console.log('2: end');
Step by step
- It prints
1: start. - setTimeout gives the callback to a timer. Even with 0 ms, it can only run once all the current code has finished.
.then registers a callback for when the promise is ready. This promise is ready already, but the callback still waits for the script to finish.- The script has finished: the call stack is empty.
- First the event loop runs promise callbacks (microtasks), before any timer.
- It prints
3: promise. - Only now does the timer's callback run, though its 0 ms were up long ago.
- It prints
4: timer.
Common mistakes
- Expecting setTimeout(fn, 0) to run immediately
Best practices
- Never block the main thread with long loops
Key takeaways
- JavaScript runs one thing at a time, on one call stack.
- Callbacks wait until the stack is empty.
- Promise callbacks run before timer callbacks.
Check yourself
Order: sync log, promise.then, setTimeout 0?
Answer: sync, promise, timeout
setTimeout(f, 0) runs f?
Answer: After the current code finishes
← Map and Set · Promises →
More in Asynchronous JavaScript