Callbacks & the Event Loop
JavaScript runs your code on a single thread: it can only do one thing at a time. Yet web pages wait for timers, clicks and network replies without freezing. The secret is callbacks plus the event loop, the system that decides when each waiting piece of code gets its turn. Understanding it explains why code doesn't always run in the order it is written.
Callbacks
A callback is a function you pass to another function so it can be called later. Some callbacks run immediately, as part of the call:
const prices = [20, 50, 10];
prices.forEach((price) => console.log(price * 2)); // synchronous callback
console.log("finished");
Others are asynchronous: they run at some point in the future, after something has happened. setTimeout(callback, ms) asks the browser to run a function after at least ms milliseconds, and addEventListener runs one whenever an event fires.
console.log("1. Order placed");
setTimeout(() => console.log("3. Chapati is ready"), 2000);
console.log("2. Waiting at the counter...");
The third line appears two seconds later. JavaScript didn't stop and wait; it handed the timer to the browser, carried on with the next line, and ran the callback when the time was up. Even setTimeout(fn, 0) runs after the current code finishes, as you will see below.
The pieces of the event loop
- Call stack: where JavaScript runs functions, one at a time. When a function is called it goes on top; when it returns it comes off.
- Web APIs: features the browser provides outside JavaScript, such as timers,
fetchand DOM events. They do the waiting. - Task queue (also called the macrotask or callback queue): callbacks from timers and events wait here once they are ready.
- Microtask queue: a higher-priority queue for promise callbacks (
.then,.catch, code afterawait) andqueueMicrotask(). - Event loop: a loop that repeats forever. Whenever the call stack is empty, it runs every microtask in the queue, then takes one task from the task queue, and goes round again (the browser can also repaint the screen between tasks).
Predicting the order
Trace this example with the figure in mind:
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
queueMicrotask(() => console.log("D"));
console.log("E");
Alogs straight away (synchronous code on the stack).setTimeouthands its callback to the browser's timer. After 0 ms it moves to the task queue.- The promise is already resolved, so its
.thencallback goes to the microtask queue, followed by thequeueMicrotaskcallback. Elogs. The script ends and the stack is empty.- The event loop empties the microtask queue first:
C, thenD. Only then does it take the timer task:B.
Microtasks can even schedule more microtasks, and they all run before the next task. Here is a slightly harder one:
setTimeout(() => console.log("timeout 1"), 0);
Promise.resolve()
.then(() => {
console.log("promise 1");
setTimeout(() => console.log("timeout 2"), 0);
})
.then(() => console.log("promise 2"));
console.log("sync");
When the first .then callback finishes, the second one is queued as a new microtask and runs immediately after, still ahead of both timers. The timers then run in the order they were scheduled.
Don't block the stack
While the call stack is busy, nothing else can happen: no clicks, no timers, no repainting. A long loop freezes the page.
const start = Date.now();
setTimeout(() => console.log("Timer fired after", Date.now() - start, "ms"), 100);
while (Date.now() - start < 1000) {
// busy for one whole second
}
The timer asked for 100 ms but had to wait until the loop released the stack (your number may be a few milliseconds higher). The delay you give setTimeout is a minimum, not a promise of exact timing.
Callback hell
When one asynchronous step depends on another, callbacks get nested inside callbacks:
setTimeout(() => {
console.log("Boil water");
setTimeout(() => {
console.log("Add tea leaves");
setTimeout(() => {
console.log("Add milk and sugar");
}, 1000);
}, 1000);
}, 1000);
This "pyramid of doom" becomes hard to read and even harder to add error handling to. Promises and async/await were created to flatten it.
Writing setTimeout(showMessage(), 2000). The brackets call showMessage immediately and pass its return value to setTimeout, so there is no delay. Pass the function itself: setTimeout(showMessage, 2000) or setTimeout(() => showMessage("Karibu"), 2000).
Key points
- A callback is a function passed to be called later; asynchronous callbacks run after the current code finishes.
- The browser's Web APIs do the waiting; ready callbacks wait in queues for an empty call stack.
- The event loop runs all microtasks (promise callbacks) before the next task (timers, events), so promises beat
setTimeout(fn, 0). - Long-running code blocks everything, and
setTimeoutdelays are minimums.
Tip: use the ← and → keys to move between pages.
