Event Loop in the Web Browser
What is the Event Loop in a Web Browser?
- JavaScript on the page runs on a single main thread, so it executes only one piece of JavaScript at a time.
- But network requests, timers, and file uploads finish at unpredictable times. How does the page keep working while it waits?
- The Event Loop solves this. To understand it, you need four parts: the Call Stack, Web APIs, the Microtask Queue, and the Macrotask (Task) Queue.
Call Stack
- The Call Stack tracks which function is currently running.
- When a function is called, it is pushed onto the top of the stack. When it returns, it is popped off.
- The engine always executes the function at the top of the stack.
- While the stack is busy, nothing else on the main thread can run: no other callbacks, no click handlers, and no rendering. A long-running loop freezes the page.
function multiply(a, b) { return a * b; }
function square(n) { return multiply(n, n); }
console.log(square(4));
// Stack grows: square -> multiply, then unwinds and logs 16
Web APIs
- Asynchronous operations like
setTimeout,fetch, DOM events, and file reading are provided by the browser, not by the JavaScript language itself. - The browser handles the waiting outside the Call Stack, so the main thread can keep running other code.
- When the operation is ready (the timer expires, the response arrives, the user clicks), the browser schedules the callback in the appropriate queue. The callback does not run immediately; it waits for its turn.
Microtask Queue
- Holds small, high-priority callbacks that should run as soon as the current JavaScript finishes.
- Sources:
- Promise callbacks:
.then(),.catch(),.finally() - The code after
awaitin anasyncfunction queueMicrotask()MutationObservercallbacks
- Promise callbacks:
- The entire Microtask Queue is drained every time it runs, including microtasks added while draining.
Macrotask Queue (Task Queue)
- Holds larger units of work, processed one task per event loop turn.
- Sources:
- Timer callbacks:
setTimeout,setInterval - User input and DOM events: click, keypress, scroll
- Network events,
postMessage,MessageChannel - Running the initial
<script>itself is a task
- Timer callbacks:
- The HTML specification just calls these "tasks". "Macrotask" is the common informal name. Browsers can keep several task queues and may prioritize some, such as user input.
The role of the Event Loop
- The Event Loop coordinates when queued callbacks can run. Each turn works roughly like this:
- Take the oldest task from a task queue and run it until the Call Stack is empty.
- Run all pending microtasks, including any new ones they create.
- If it is time for a new frame, render: run
requestAnimationFramecallbacks, recalculate styles, layout, and paint. - Repeat.
- So: current task → all microtasks → maybe render → next task.
- At 60 frames per second, the browser has about 16.7 ms per frame. A task that runs longer delays rendering and makes the page feel janky.
Example
console.log("Start");
setTimeout(() => console.log("Timeout"), 0);
Promise.resolve("Promise").then((value) => console.log(value));
console.log("End");
Output:
Start
End
Promise
Timeout
console.log("Start")andconsole.log("End")are synchronous, so they run first on the Call Stack.setTimeouthands the callback to the browser's timer. After 0 ms, the callback is queued in the Task Queue.- The resolved Promise queues its
.then()callback in the Microtask Queue. - When the script finishes and the stack is empty, microtasks run first, so
Promiseis logged. - Only then does the event loop pick the next task, and
Timeoutis logged.
Practice: predict the output
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
queueMicrotask(() => console.log("4"));
(async () => {
console.log("5");
await null;
console.log("6");
})();
console.log("7");
Answer: 1 5 7 3 4 6 2
1,5, and7are synchronous. The body of an async function runs synchronously until the firstawait.3,4, and6are microtasks, executed in the order they were queued.2is a timer task, so it runs last.
Visualize event loop examples step by step
Important qualifications
setTimeout(fn, 0)is not immediate. It means "run after at least 0 ms, as a later task". Browsers also clamp deeply nested timers to at least 4 ms, and inactive tabs may throttle timers further.- Microtasks can starve the page. A microtask that keeps queuing more microtasks never lets the loop reach rendering or the next task, which freezes the page just like an infinite loop.
- Async does not mean parallel.
async/awaitonly changes when your code runs; CPU-heavy JavaScript still blocks the main thread. Split long work into smaller tasks, or move it to a Web Worker, which has its own thread and event loop. - Use
requestAnimationFramefor visual updates. It runs right before the browser paints the next frame. - Node.js is different. Node uses libuv with event loop phases (timers, poll, check, and more) and has
process.nextTick(), which runs before Promise microtasks. The browser model on this page does not map exactly to Node.
Takeaway
- Call Stack: executes JavaScript, one function at a time.
- Web APIs: let the browser handle asynchronous work outside the stack.
- Microtask Queue: Promise and
awaitcallbacks, fully drained after each task. - Macrotask Queue: timers, events, and other tasks, one per loop turn.
- Event Loop: when the stack is empty, it runs all microtasks, lets the browser render, then picks the next task.