The event loop is the mechanism that coordinates the call stack, the Web APIs, and the two queues. Understanding it precisely will explain every "why does this log in this order?" question you will ever encounter.
The Call Stack
The call stack is a LIFO (last in, first out) data structure that tracks function execution. When you call a function, a frame is pushed onto the stack. When it returns, the frame is popped. JavaScript cannot execute the next thing until the current stack frame returns — this is what "single-threaded" means in practice.
function c() { return 1; }
function b() { return c(); }
function a() { return b(); }
// Stack during a():
// [a] → [a, b] → [a, b, c] → [a, b] → [a] → []
a();Web APIs — Outside the JS Engine
Browsers provide APIs like setTimeout, fetch, and DOM event listeners. When you call setTimeout(fn, 1000), the JS engine hands the timer off to the browser's timer API and immediately returns. The browser runs the timer in its own system — completely outside the JS engine — and pushes fn onto the callback queue when the delay expires.
Microtask Queue vs Callback Queue
There are two queues, not one, and they have different priorities:
- Microtask Queue — holds Promise callbacks (
.then(),.catch()),queueMicrotask(fn), andMutationObservercallbacks. This queue drains completely before any callback task runs. - Callback Queue (Task Queue) — holds setTimeout, setInterval, and I/O callbacks. The event loop takes one task per iteration.
The Event Loop Algorithm
The event loop runs a continuous loop:
- If the call stack is not empty, execute the top frame.
- When the stack empties, drain the microtask queue completely.
- Take ONE task from the callback queue and push it onto the stack.
- Repeat.
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");
// Output: 1, 4, 3, 2
//
// Why?
// "1" → synchronous, runs immediately on the call stack
// setTimeout → schedules callback in the Callback Queue
// Promise.resolve().then → schedules callback in the Microtask Queue
// "4" → synchronous, runs immediately
// Call stack empties → drain microtasks: "3" runs
// Microtask queue empty → take from callback queue: "2" runssetTimeout(fn, 0) does not mean "run immediately." It means "run after the current task and all microtasks have finished." The minimum delay is 0ms in theory, but the actual delay depends on how busy the event loop is — it could be many milliseconds if the stack is backlogged.Starvation Risk
Because microtasks drain completely before any callback task runs, a microtask that keeps scheduling new microtasks can starve the callback queue indefinitely. This is why you should never put infinite loops in .then() chains or queueMicrotask.
.then()), you can block setTimeout callbacks from ever running. The browser will not freeze (the stack is empty), but timers and I/O will be delayed indefinitely.Step-by-Step Execution Trace
Walk through this snippet line by line. Predict the output before reading the explanation:
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve()
.then(() => console.log('3'))
.then(() => console.log('4'));
queueMicrotask(() => console.log('5'));
console.log('6');
// Output: 1, 6, 3, 5, 4, 2queueMicrotask('5') fires before .then('4') even though Promise.resolve().then('3') was registered first. That is because .then('4') is chained on the result of .then('3') — it cannot be queued until '3' completes.