Understanding the JavaScript Event Loop
Why does JavaScript feel single-threaded yet handle so much at once? The event loop is the answer. Here's a clear mental model with examples you can run.
JavaScript runs on a single thread, yet it juggles network requests, timers, and clicks without freezing. The mechanism that makes this possible is the event loop. Understanding it explains a lot of “why did that run in that order?” surprises.
The pieces
- Call stack — where functions execute, one at a time.
- Web APIs — browser (or Node) features like timers and fetch that do work off the main thread.
- Task queue (macrotasks) — callbacks waiting to run, e.g.
setTimeout. - Microtask queue — higher-priority callbacks, e.g. resolved Promises.
The event loop’s job: when the call stack is empty, run everything in the microtask queue, then take one task from the task queue, and repeat.
A classic example
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");
The output is 1, 4, 3, 2. Synchronous code runs first (1, 4). Then the loop drains microtasks (3, the Promise) before macrotasks (2, the timer) — even though the timer was set to 0.
Why microtasks beat timers
After each task, the loop empties the entire microtask queue before moving on. So Promise callbacks always run before the next setTimeout. Chaining lots of microtasks can even starve timers — something to watch for in tight loops.
Practical takeaways
setTimeout(fn, 0)does not run immediately — it waits for the current work and all microtasks to finish.awaitis Promise-based, so continuations afterawaitare microtasks.- Long synchronous work blocks everything, including rendering. Break it up or move it to a Web Worker.
Once you picture the stack draining, then microtasks, then one macrotask, the ordering stops being mysterious.
Tagged
Keep reading
Getting Started with TypeScript: A Practical Guide
TypeScript adds a safety net to JavaScript without slowing you down. Here's how to set it up, the handful of concepts that matter, and how to adopt it gradually.
HTTPS Explained: What Happens When You Visit a Site
The padlock in your address bar hides a clever handshake. Here's what actually happens when you load an HTTPS site — encryption, certificates, and trust.
CSS Grid vs. Flexbox: When to Use Each
Grid and Flexbox aren't rivals — they solve different problems. A simple rule of thumb, with examples, for choosing the right layout tool every time.