Lesson 6 of 12 · 11 min · Asynchronous JavaScript
The event loop: how JavaScript runs asynchronous code
What you will learn
- Why JavaScript has one thread and how it still does many things at once
- The call stack, Web APIs, task queue and microtask queue
- The exact order of
setTimeout, promises and synchronous code - What blocks the event loop and how to avoid it
- How Web Workers and Node.js fit in
In simple words
JavaScript has just one cook in the kitchen. The cook can only do one thing at a time, but they do not stand around waiting for the oven: they put the dish in, set a timer, and carry on with the next order. When the timer rings, the finished dish joins a queue and the cook picks it up when free. The event loop is the rule for deciding what the cook does next. Understanding it explains why some code runs "later" and why a long task freezes the whole page.
Words to know
- Call stack: the list of functions currently running, one on top of another.
- Callback: a function you hand over to be called later.
- Task queue: where finished timers, clicks and network events wait for their turn.
- Microtask queue: a higher-priority queue used by promises.
One thread
A browser tab (and a Node.js process) runs your JavaScript on one main thread. Code runs to completion: while one function runs, nothing else in your JavaScript can run, and in a browser the page cannot paint or respond to clicks either (it shares the thread with rendering). That is why long loops freeze a page.
Yet a page can fetch data, wait for timers and handle clicks at once, because waiting is not done by JavaScript. The browser (or Node.js) provides Web APIs (timers, fetch, DOM events, geolocation) that run outside your code, often in other threads. When they finish, they put a callback into a queue for the event loop to run.
The pieces
- Call stack: where synchronous code runs. A function call is pushed, its return pops it. If it is empty, JavaScript is idle.
- Web APIs: timers, network, DOM events (outside the stack).
- Task queue (macrotask queue): callbacks from timers, UI events,
MessageChanneland similar. Each is a task. - Microtask queue: callbacks from promises (
.then,.catch,awaitcontinuations),queueMicrotask, andMutationObserver. - The event loop: repeatedly: run one task from the task queue; then run all microtasks until the microtask queue is empty; then (in a browser) possibly render; then take the next task.
┌─────────────┐ ┌────────────┐
│ call stack │◄───────│ event loop │◄── microtask queue (promises) runs first, fully
└─────────────┘ │ │◄── task queue (timers, events) runs one at a time
│ └────────────┘
▼
Web APIs (timers, fetch, events) run outside, then enqueue callbacks
Order of execution
console.log("1: start");
setTimeout(() => console.log("2: timeout"), 0);
Promise.resolve().then(() => console.log("3: promise"));
queueMicrotask(() => console.log("4: microtask"));
console.log("5: end");
The output is:
1: start
5: end
3: promise
4: microtask
2: timeout
Why: the synchronous lines run first on the call stack ("1", then "5"). setTimeout hands its callback to the timer API, which enqueues it as a task after at least 0 ms. The promise callback and queueMicrotask are microtasks. When the stack is empty, the loop runs all microtasks ("3", "4") before the next task ("2"). So: sync code, then microtasks, then tasks.
await is the same machinery: the code after await x is a microtask continuation.
async function run() {
console.log("a");
await null; // the rest becomes a microtask
console.log("b");
}
run();
console.log("c");
// a, c, b
setTimeout is not exact
setTimeout(fn, 1000) means "run no sooner than about 1000 ms from now, when the loop is free". If the main thread is busy for 3 seconds, the callback waits. Browsers also clamp nested timers and throttle timers in background tabs (to about once a second or less). Do not use timers to measure time precisely: use performance.now() and Date.now() differences. setTimeout(fn, 0) just defers to a later task ("yield to the loop"), and requestAnimationFrame runs before the next paint (the rendering lesson).
Blocking the event loop
button.addEventListener("click", () => {
const start = Date.now();
while (Date.now() - start < 3000) {} // busy-wait 3 seconds
console.log("done");
});
For those 3 seconds the page cannot respond to clicks, scrolling, or even repaint a loading spinner: the thread is occupied. Typical causes: huge loops, parsing a giant JSON, heavy computations (image processing, sorting millions of items), synchronous XHR, and expensive rendering. Remedies:
- Do less work: better algorithms, smaller data, pagination.
- Chunk the work and yield between chunks so input and paint can happen:
async function processAll(items) {
for (let i = 0; i < items.length; i++) {
handle(items[i]);
if (i % 500 === 0) await new Promise(resolve => setTimeout(resolve, 0)); // let the loop breathe
// or: await scheduler.yield(); where supported
}
}
- Use Web Workers for heavy computation in a separate thread (below).
- Never wait with a busy loop; use timers and promises.
A microtask loop can also starve rendering: a promise that keeps scheduling new microtasks never lets the loop reach the next task or a paint.
Web Workers
A Web Worker runs JavaScript on another thread, with its own event loop, no DOM access, and communication by messages (postMessage, copied with the structured clone algorithm):
// main.js
const worker = new Worker(new URL("./sum-worker.js", import.meta.url), { type: "module" });
worker.postMessage(bigArray);
worker.onmessage = (event) => console.log("sum:", event.data);
// sum-worker.js
self.onmessage = (event) => {
const total = event.data.reduce((a, b) => a + b, 0);
self.postMessage(total);
};
Use workers for CPU-heavy work (parsing large files, crypto, image filters), keeping the page responsive. Related: service workers (network proxy and offline caching) and OffscreenCanvas.
Node.js
Node.js has the same idea with different pieces: the libuv library runs the loop and a thread pool for file system and crypto work. Its loop has phases (timers, pending callbacks, poll for I/O, setImmediate checks, close callbacks), plus the microtask queues: process.nextTick callbacks run before promise microtasks. So in Node.js:
setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
process.nextTick(() => console.log("nextTick"));
Promise.resolve().then(() => console.log("promise"));
// nextTick, promise, then timeout and immediate (their relative order can vary from the main module)
The practical rule for Node.js servers is the same: never block the loop (CPU-heavy work or synchronous file reads such as fs.readFileSync in a request handler stall every user); use worker_threads or a separate service for heavy computation.
Interview-ready summary
"JavaScript runs one thing at a time on the call stack. Asynchronous operations (timers, network, events) are handled by the environment's Web APIs, which later place callbacks in queues. The event loop moves a callback onto the stack only when the stack is empty: it runs one macrotask, then drains all microtasks (promise callbacks), then renders if needed. That is why promise .then callbacks run before setTimeout(..., 0), and why a long synchronous task freezes the page."
Common mistakes
- Thinking
setTimeout(fn, 0)runs immediately. - Expecting precise timer delays.
- Long synchronous loops in event handlers or request handlers.
- Assuming JavaScript is multithreaded and sharing state between threads without messages.
- Confusing the order of promises and timers in interview puzzles.
- Using
asyncfunctions as if they ran in parallel threads (they only interleave on one thread).
Try it yourself
- Predict the output of the five-line example, then run it.
- Add
awaitandasyncfunctions to a puzzle and trace which parts are microtasks. - Write a click handler with a 3-second busy loop and try to scroll the page; then fix it by chunking.
- Move a heavy loop into a Web Worker and show that the page stays responsive.
- Compare
setTimeout(0),queueMicrotaskandrequestAnimationFrameorder with logs.
Check yourself
Why do promise callbacks run before setTimeout callbacks with a delay of 0?
Promise callbacks are microtasks, which the event loop drains completely after the current task; timer callbacks are tasks that wait in the task queue for the next turn.
What does it mean that JavaScript is single-threaded?
Your JavaScript code runs on one main thread, executing one piece at a time; concurrency comes from the environment handling waiting operations and queuing callbacks.
What blocks the event loop?
Long-running synchronous code, such as big loops or heavy parsing, because nothing else (including rendering and input handling) can run until it finishes.
What can you use to run heavy computation without freezing the page?
A Web Worker, which runs on a separate thread and communicates through messages.
Interview questions
Explain the JavaScript event loop.
The call stack runs synchronous code. Async operations are delegated to Web APIs, whose callbacks go into the task queue (or the microtask queue for promises). When the stack is empty, the event loop runs one task, then all microtasks, renders if needed, and repeats.
What is the difference between microtasks and macrotasks?
Microtasks (promise reactions, queueMicrotask) are processed completely after each task and before rendering; macrotasks (timers, UI events, I/O callbacks) are processed one per loop turn.
Predict the output: console.log(1); setTimeout(() => console.log(2)); Promise.resolve().then(() => console.log(3)); console.log(4);
1, 4, 3, 2: synchronous logs first, then the microtask, then the timer task.
Summary
- JavaScript runs on one thread; Web APIs handle waiting and queue callbacks.
- The event loop runs one task, then all microtasks (promises), then may render.
- Order: synchronous code, microtasks, then tasks; timers are not exact.
- Never block the loop: chunk work, use Web Workers, and avoid synchronous heavy work in Node.js handlers.
Going deeper
- MDN: The event loop: the concurrency model explained.
- MDN: Using microtasks: how microtasks and tasks differ.
- MDN: Using Web Workers: threads in the browser.
- Node.js: The event loop, timers and nextTick: the Node.js phases.
See how much of this you can explain
A free mock interview asks you new questions on JavaScript from fundamentals to async for Frontend Developer and scores every answer, with what to fix.