Chapter 13 Cheatsheet: The Event Loop
This cheatsheet summarizes the mechanics of JavaScript’s concurrency model covered in Chapter 13.
Core Concepts
- Single-Threaded: JavaScript executes code on a single main thread. It can only process one instruction at a time.
- Non-Blocking: JavaScript delegates slow, I/O bound operations (networks, timers) to the background so the main thread never freezes.
- External APIs: The browser (or Node.js) handles the actual background work on separate C++ threads and pushes the results back to JavaScript when they finish.
The Three Execution Areas
1. The Call Stack (Synchronous) Where standard function calls are pushed and executed. It must be completely empty before background tasks are allowed to run.
2. The Microtask Queue (High Priority)
Where Promise callbacks (.then, .catch, await) are queued. The Event Loop empties this queue entirely before looking at the standard Task queue.
3. The Task Queue (Low Priority)
Where standard callbacks (setTimeout, DOM events) are queued. Also called the Macrotask Queue.
The Event Loop Cycle
The Event Loop is an infinite loop constantly checking these areas in this exact order:
- Execute everything currently on the Call Stack until it is completely empty.
- Check the Microtask Queue. Execute all pending microtasks until this queue is completely empty. (If a microtask spawns another microtask, keep executing them).
- Check the Task Queue. Pull out the first pending task, push it to the Call Stack, and execute it.
- Return to Step 1.