The Event Loop from Scratch
The event loop connects the call stack, Web APIs, callback queue, and microtask queue. Understanding it is understanding async JavaScript.
Web APIs handle async work. Callbacks go to the callback queue, Promises go to the microtask queue. The event loop moves callbacks to the stack when it is empty. Microtasks always run first.
EXERCISE
1Web APIs: The Browser Superpowers
setTimeout, fetch, console.log, document methods... none of these are JavaScript. They are Web APIs provided by the browser. Understanding this split is essential.
The language is smaller than most people assume. Variables, functions, objects, loops, operators and the call stack are all it defines. Timers, network requests, the DOM and storage are not part of it; they are provided by whatever the engine is running inside.
const total = 10;
function add(a, b) {
return a + b;
}
if (total > 5) {
add(1, 2);
}
Every line of that is ECMAScript, and behaves identically in a browser, in , and anywhere else.
setTimeout(handler, 1000);
document.getElementById("app");
fetch("https://example.com");
localStorage.setItem("key", "value");
None of those appear in the specification. In a browser they are Web APIs, exposed on window, and JavaScript calls them the same way it calls anything else on the global object.
The distinction is not pedantry. It is the answer to how a single-threaded language does several things at once:
console.log("first");
setTimeout(function () {
console.log("third");
}, 2000);
console.log("second");
The engine did not wait two seconds and did not run anything in parallel. It called the browser's timer , which counts on its own, and went straight to the next line. The counting happened outside JavaScript entirely, on machinery the browser owns.
That is why the environment matters so much:
const fs = require("fs");
fs.readFile("data.txt", "utf8", function (err, contents) {
console.log(contents);
});
Node has no window, no document and no fetch in older versions, because there is no page. It has a file system and processes instead. The language is identical; the surroundings are not, and the surroundings are where all the asynchronous capability lives.
The pieces this unit needs are now in place. JavaScript has one call stack. The environment has APIs that can do work independently. What remains is the question of how a finished callback gets back onto the stack, which is the event loop.
One practical consequence before moving on: an API missing from the environment fails with the same error as a misspelled variable, because that is exactly what it is.
document.getElementById("app");
// ReferenceError: document is not defined (in Node)
require("fs");
// ReferenceError: require is not defined (in a browser)
Neither message mentions environments. The global object was asked for a name it does not have, and answered accordingly.
EXERCISE
2The Event Loop, Callback Queue, and Microtask Queue
The event loop is a simple gatekeeper: it checks if the call stack is empty, and if the queue has a callback waiting, it pushes the callback onto the stack.
When a Web API finishes its work, the callback cannot simply run. The thread might be busy, and interrupting it would reintroduce exactly the problems a single thread avoids. So finished callbacks wait in a queue, and something moves them onto the stack when it is safe.
That something is the event loop, and its rule is short: when the call stack is empty, take the next waiting callback and push it on.
There are two queues, not one, and the difference decides ordering.
The microtask queue holds promise callbacks and a few similar things. The callback queue, often called the macrotask or task queue, holds timers, click handlers, and network callbacks. Microtasks have absolute priority: the loop empties that queue completely before taking a single item from the other.
console.log("1: sync");
setTimeout(function () {
console.log("2: timeout");
}, 0);
Promise.resolve().then(function () {
console.log("3: promise");
});
console.log("4: sync");
The output is 1: sync, 4: sync, 3: promise, 2: timeout.
Both synchronous lines run first, because they are on the stack and nothing preempts running code. Then the stack empties and the loop looks at the microtask queue first, finding the promise callback. Only once that queue is empty does it take the timer, even though the timer was registered earlier and asked for zero delay.
The priority is absolute, which is worth proving:
setTimeout(() => console.log("timeout"), 0);
Promise.resolve()
.then(() => console.log("promise 1"))
.then(() => console.log("promise 2"))
.then(() => console.log("promise 3"));
All three promise callbacks run before the timer. Each then schedules another microtask, and the loop keeps draining that queue until it is empty. A timer registered first still waits.
That behaviour has a sharp edge. A microtask that schedules another microtask forever will starve the callback queue completely:
function loop() {
Promise.resolve().then(loop);
}
The queue never empties, so no timer, no click and no render ever runs again. The page is frozen as thoroughly as by a while loop, and the stack looks idle the whole time.
Pro Tip: "Asynchronous" does not mean "in parallel". Every one of these callbacks runs on the same single thread, one at a time. What is concurrent is the waiting, which happens outside JavaScript.
EXERCISE
3Tracing the Event Loop Step by Step
The best way to understand the event loop is to trace through a complex example and predict the exact output order.
The rules are short enough to recite. The way to be sure you have them is to a program that mixes all four cases and predict its output before running it.
console.log("A");
setTimeout(function () {
console.log("B");
}, 0);
Promise.resolve().then(function () {
console.log("C");
});
console.log("D");
Take it in order. A prints immediately. The timer is handed to the browser and its callback will join the callback queue once zero milliseconds have passed, which is essentially at once. The promise is already resolved, so its callback goes straight to the microtask queue. D prints.
Now the stack is empty and the loop takes over. Microtasks first: C. Then, with that queue empty, one task: B.
Output: A, D, C, B.
A harder one, with work nested inside a callback:
console.log("start");
setTimeout(function () {
console.log("timeout 1");
Promise.resolve().then(function () {
console.log("promise inside timeout");
});
}, 0);
setTimeout(function () {
console.log("timeout 2");
}, 0);
Promise.resolve().then(function () {
console.log("promise 1");
});
console.log("end");
The synchronous lines go first: start, end. The stack empties, and the microtask queue is drained: promise 1. Then one task runs: timeout 1. That callback schedules a microtask before it finishes.
Here is the part people get wrong. The loop does not move on to timeout 2 next. After every single task it drains the microtask queue again, so promise inside timeout runs before the second timer.
Output: start, end, promise 1, timeout 1, promise inside timeout, timeout 2.
The full cycle, stated once:
1. run everything on the stack until it is empty
2. drain the ENTIRE microtask queue
3. take ONE task from the callback queue and run it
4. go back to step 2
Step 2 sitting between every task is the detail that decides most interview questions on this topic, and the reason a promise scheduled inside a timer beats a timer scheduled before it.
Pro Tip: When output order surprises you, write down which queue each callback entered and when. The loop has no other rules, so the answer is always in that list.
