Event Loop
The mechanism that lets JavaScript handle many tasks without ever running two at once.
What is it?
JavaScript does one thing at a time: it has a single "thread". Yet it handles timers, network requests and clicks seemingly "at once" without freezing the page. The event loop makes this possible.
It separates "run this now" from "run this later, once something finishes", and keeps checking whether any waiting code is ready to run.
Explain like I'm 10
Picture one chef who cooks one dish at a time but has an oven timer for things in the background. The chef finishes the current dish, checks whether any timers went off, handles those, then moves on. Never two things at once, but never idle.
Examples
Order of execution
console.log("1: start");
setTimeout(() => {
console.log("2: timeout callback");
}, 0);
console.log("3: end");
// Output order:
// 1: start
// 3: end
// 2: timeout callbackEven with a 0ms delay, the timeout callback runs after all the regular code, because it waits for the main code to finish.
Promises run before timers
console.log("1: start");
setTimeout(() => console.log("2: setTimeout"), 0);
Promise.resolve().then(() => console.log("3: promise"));
console.log("4: end");
// Output order: 1, 4, 3, 2Promise callbacks (microtasks) always run before the next timer callback (a macrotask), even if both were scheduled at about the same time.
How it works
JavaScript runs your main code on the call stack. Async work (like setTimeout or a network request) is handed to the browser, and JavaScript keeps running the rest of the code. When the async task finishes, its callback goes into one of two queues:
- Microtask queue: promise callbacks.
- Macrotask queue: timers, network events and clicks.
Once the call stack is empty, the event loop drains the entire microtask queue, including microtasks added while draining. Only then does it run a single macrotask, and then it checks the microtask queue again.
Call stack (running now)
↓ empty?
Event loop checks the queue
↓
Queue has a waiting callback? ──▶ run it on the call stack
↓ no
keep checkingWhy does it exist?
Without it, any slow task (like a network request) would freeze the page until it finished. The event loop lets JavaScript start slow tasks, move on, and handle the result later, so the page stays responsive.
When to use it
Use this mental model when debugging surprising order: why a console.log ran before a network response, why setTimeout(fn, 0) didn't run immediately, or why the page froze during a long calculation.
When not to use it
You never manage the event loop directly; there's no API to configure it. You don't "use" it. You understand it so that promises, timers and events make sense instead of feeling random.
Common mistakes
Assuming
setTimeout(fn, 0)runs immediately. It still waits for the current code to finish.Not realizing a long synchronous loop can freeze the page, since nothing else runs until the call stack is clear.
Mixing up the order of promise callbacks (microtasks) and timer callbacks (macrotasks). Microtasks always finish draining before the next macrotask runs; it's a rule, not a tendency.
Practice exercises
- Easy:
Predict, then verify, the console output order of a mix of
console.logandsetTimeoutcalls. - Medium:
Write a small snippet mixing a
Promise.resolve().then()and asetTimeout, and explain which runs first and why. - Hard:
Explain, in your own words, why a
forloop with a billion iterations would freeze a webpage.
Interview questions
Is JavaScript single-threaded?
Yes. It runs one piece of code at a time on a single call stack. The browser or Node.js does slow work (timers, network, file I/O) in the background and hands results back to that thread through the event loop.
What is the difference between the call stack and the task queue(s)?
The call stack is where code is running right now, one function frame at a time. The task queues hold waiting callbacks (from timers, promises, DOM events) that can only run once the stack is completely empty.
Do microtasks (promises) or macrotasks (`setTimeout`) run first?
Microtasks. Every time the call stack empties, the event loop drains the entire microtask queue, including microtasks added while draining, before running a single macrotask.
What concretely counts as a macrotask versus a microtask?
Macrotasks are tasks from the host environment: setTimeout/setInterval callbacks, DOM events (clicks, keypresses) and network callbacks. Microtasks are jobs scheduled by the JavaScript engine: promise .then()/.catch()/.finally() callbacks and queueMicrotask() callbacks. Microtasks always run before the next macrotask.
Where does `queueMicrotask()` fit relative to promise callbacks?
It uses the same microtask queue as promise callbacks, so the same rule applies: it runs after the current synchronous code and before the next macrotask, in the order it was queued among other microtasks.
Predict the output: `console.log(1); setTimeout(() => console.log(2), 0); Promise.resolve().then(() => console.log(3)); console.log(4);`
1, 4, 3, 2. The two synchronous logs run first. Once the stack is empty, the microtask queue drains, so the promise logs 3. Only then does the event loop run the timer macrotask and log 2.
What does it actually mean that 'the call stack must be empty' before the event loop can act?
The event loop never interrupts running JavaScript to run a queued callback. It only checks the queues once every function on the stack has returned. So a long synchronous operation delays every pending timer, promise callback and UI event, however long they've waited.
Why doesn't `setTimeout(fn, 0)` run its callback immediately?
A timer callback is a macrotask, so it waits for the current synchronous code to finish and for the microtask queue to drain. 0 means 'as soon as possible after that', not 'right now'. Browsers also clamp very short or deeply nested timeouts to a small minimum delay.
Does the event loop run through the entire macrotask queue in one go, the way it drains the whole microtask queue?
No. It takes one macrotask per pass, then drains the whole microtask queue again before the next macrotask. The microtask queue is always fully emptied; the macrotask queue is not.
Predict the output: two `setTimeout(fn, 0)` calls are scheduled, and inside the first timer's callback a `Promise.resolve().then()` is scheduled. Does that promise callback run before or after the second timer's callback?
Before the second timer. When the first timer (a macrotask) finishes, the event loop drains the microtask queue, including the promise callback just scheduled, before moving on to the second timer, even though that timer was scheduled earlier.
If a microtask callback schedules another microtask, does the event loop wait for that one too before moving to the next macrotask?
Yes. The rule is 'drain the microtask queue until it's empty', not 'run what was there at the start'. Microtasks added while draining run in the same pass, before any macrotask.
Why can a chain of promises that keeps scheduling new microtasks prevent timers from ever firing, a phenomenon sometimes called 'microtask starvation'?
The event loop only moves to a macrotask once the microtask queue is empty. A promise chain that keeps re-scheduling itself (each .then() queuing another) never lets it empty. Pending setTimeout callbacks, UI events and network callbacks are starved forever, even though nothing is 'blocking' in the synchronous sense.
Where do browser rendering and repaints happen relative to microtasks and macrotasks?
A browser usually repaints after the microtask queue drains and before the next macrotask (though not necessarily every cycle). That's why an endless stream of microtasks can freeze rendering too, not just logic.
What is `requestAnimationFrame`, and how does its timing differ from a macrotask like `setTimeout`?
It runs a callback right before the browser's next repaint, in sync with the display's refresh rate, instead of after a delay like setTimeout. It's meant for visual updates, so the browser can time them correctly. A generic timer has no link to the paint cycle.
Predict the output: a script logs 'start', calls `queueMicrotask` to log 'micro', calls `setTimeout(fn, 0)` to log 'macro', then logs 'end'.
'start', 'end', 'micro', 'macro'. The synchronous logs run first. Once the stack empties, the microtask queue drains ('micro'), and only then does the timer macrotask log 'macro'.
What does 'blocking the event loop' mean, concretely?
Running synchronous JavaScript that takes a long time, so the call stack never empties. No timers fire, no promise callbacks run, and the page can't respond to clicks, scrolls or repaints, because the single thread is busy with that code.
Why can one very expensive synchronous computation freeze an entire web page, including things seemingly unrelated to it like scrolling?
Scrolling, clicks and rendering all need the same single thread to be free to run their queued callbacks. While a synchronous loop keeps the stack busy, none of them run, whatever feature they belong to, because the event loop can't interrupt running code.
Do Web Workers get around JavaScript's single-threaded limitation, and how do they relate to the main thread's event loop?
Yes. A Web Worker runs on a separate thread with its own call stack and event loop, so heavy work there doesn't block the main thread. It talks to the main thread only through messages (postMessage), which arrive as macrotask-like events on the main thread's queue. They don't share memory and state directly.
Conceptually, how does Node.js's event loop differ from a browser's?
Same core idea: one thread, a call stack, and queues drained when the stack is empty. But Node.js splits macrotasks into phases (timers, I/O callbacks, setImmediate, close callbacks, and so on) that run in a fixed order each loop. A browser's model is simpler and doesn't expose phases.
Predict the output: an `async` function awaits an already-resolved value and logs after the `await`; a `setTimeout(fn, 0)` is scheduled right before calling that async function; a synchronous log happens right after calling it.
The synchronous log after the call runs first, then the async function's post-await log, then the timer's log. Resuming after await is a microtask, so it runs before the timer's macrotask, even though the timer was scheduled earlier.
Why does resuming after an `await` behave, timing-wise, just like a promise `.then()` callback?
Because that's what it is. await registers a continuation on a promise, and that continuation goes into the microtask queue like any .then() callback. So async/await follows the same microtask-before-macrotask rules.
Predict the output: `console.log(1); Promise.resolve().then(() => console.log(2)); Promise.resolve().then(() => console.log(3)).then(() => console.log(4)); console.log(5);`
1, 5, 2, 3, 4. The synchronous logs run first. Then microtasks run in the order they were queued: 2, then 3. The .then() that logs 4 is only queued once 3 finishes, so 4 runs last.
A `setTimeout` callback with a 100ms delay ends up running noticeably later than 100ms after it was scheduled. What event-loop-related reasons could explain that?
After 100ms the timer only becomes eligible to run. It still waits for the call stack to empty and for the microtask queue to drain. Long-running synchronous code, or a microtask queue that keeps refilling, can delay it well past 100ms.
Why is it more accurate to think of `setTimeout`'s delay as a minimum rather than a guarantee?
The delay only guarantees the callback won't run before that time. It says nothing about how soon after, because the callback still waits behind the running code, the microtask queue and any earlier macrotasks.
Why doesn't calling `Promise.all()` to wait on several promises block the event loop while they're pending?
Promise.all() doesn't loop or poll. It registers callbacks on each promise and returns immediately, so the stack clears. Nothing runs again until a promise settles and its callback is scheduled, so the thread is free for other work meanwhile.
Mechanically, why is a UI click handler just another item competing for the same queue as a `setTimeout` callback?
The browser detects the click outside JavaScript. Instead of interrupting running code, it queues the handler as a macrotask, just like a timer firing. So a page busy with a long synchronous script won't respond to a click until that script finishes.
If a piece of code schedules two `setTimeout(fn, 0)` calls back to back, does the one scheduled first always fire before the second?
Usually yes, since equal-delay timers fire in the order they became eligible. It's not absolute: browsers clamp very short or deeply nested timeouts to a small minimum delay (historically about 4ms), and other queued work can affect order in edge cases.
What's the difference, in terms of end effect versus root cause, between starving the main thread with an infinite chain of microtasks versus with one long synchronous loop?
From outside, both freeze the page: nothing else gets a turn. A synchronous loop keeps the call stack busy. A runaway microtask chain keeps emptying and refilling the microtask queue, so the stack briefly empties between each one, but the event loop never reaches the next macrotask because that queue is never finished.
Why is JavaScript's split into 'run this now' and 'run this later, once something else finishes' the whole reason the event loop needs to exist at all?
With only one thread, JavaScript can't wait for a slow operation without freezing everything. Splitting work into synchronous code plus deferred callbacks lets the thread start slow work, move on, and handle results later. The event loop manages when 'later' arrives.
What is the difference between a task and a microtask job in loose spec terms, and why does the distinction matter in practice?
A 'task' (macrotask) is host work like a timer firing or a network event. A 'microtask' (a 'job' in the spec, mostly from promises) is follow-up work scheduled by the engine. The engine always drains all pending jobs before letting the host run the next task, which is why promise callbacks beat timer callbacks with the same nominal delay.