Lesson 2
Event loop
Build a practical mental model for event loop and use it in working JavaScript.
By the end, you will be able to…
- Explain event loop in your own words
- Use event loop in a small program
- Recognize and debug a common failure mode
Build the mental model
The event loop moves finished async work from queues onto the empty call stack. Microtasks (Promise callbacks) always drain completely before the next macrotask (a timer, an event) is allowed to run.
Syntax and working example
Read the code from inputs to output. Predict what it prints, then run it and change one value.
Why this matters
This exact ordering rule — all microtasks before the next macrotask — is asked about constantly in interviews and explains subtle async bugs.
Real-world example
A UI update queued in a Promise .then() reliably runs before the next setTimeout-scheduled render, because of this exact priority.
Common mistakes
- Assuming Promises and setTimeout(fn, 0) resolve in the order they were written, ignoring queue priority
- Not knowing microtasks fully drain before the next macrotask begins
- Confusing the call stack (synchronous) with the task queues (deferred)
Try it yourself
Challenge
Predict the log order of a mix of sync code, a Promise, and a setTimeout.
Knowledge check
Which runs first once the call stack is empty: a pending Promise .then() or a pending setTimeout(fn, 0)?
Summary
The event loop always drains all pending microtasks (Promises) before running the next macrotask (timers, events).