Skip to content
FrontDepth, Home

JavaScript Deep Dive

Event Loop

How single-threaded JavaScript handles timers, network responses and user input without freezing the page: the call stack, task and microtask queues, rendering, and what this means for React and performance.

JuniorMiddleSeniorUpdated 13 November 2026

Reading level

Shows sections up to the selected level.

Before you start

No prerequisites.

This topic starts at Junior level.

JuniorConcept

What the event loop is and why JavaScript needs it

JavaScript runs your code on a single thread. At any moment exactly one piece of JavaScript is executing, and the engine keeps track of it with the : calling a function pushes a frame onto the stack, returning from it pops the frame. While something is on the stack, nothing else can run.

A web page, however, has to deal with many things that happen "at the same time": a timer expires, a network response arrives, the user clicks a button, the screen needs to be redrawn. If JavaScript had to sit and wait for each of these, the page would freeze.

So the work is split between two parts:

  • The JavaScript engine (V8, SpiderMonkey, JavaScriptCore) executes code and manages the call stack. The language itself has no timers, no network and no clicks.
  • The host environment — the browser or Node.js — provides those capabilities. In the browser they are called . The host does the waiting outside your code and, when a result is ready, queues a to run later.

The is the host's mechanism that connects the two. In simplified pseudocode:

JavaScript
while (true) {
  const task = queue.takeNext();
  task.run();
}

Each iteration takes one queued callback and runs it until the call stack is empty again. This is called run-to-completion: a running function is never interrupted halfway by another callback. It keeps code predictable — two callbacks never change the same variable at the same time — but it also means that one slow function blocks everything else on the page, including clicks and screen updates. The real loop has a few more steps (microtasks and rendering); the Middle level adds them.

"Single-threaded" refers to the page's . Web Workers run JavaScript on separate threads, and each worker has its own event loop.

JuniorWeb platform

Call stack, Web APIs and the task queue

Follow what happens with a timer:

JavaScript
console.log("one");
setTimeout(() => console.log("three"), 0);
console.log("two");
  1. console.log("one") is pushed onto the , runs and is popped.
  2. setTimeout asks the browser to start a timer and returns immediately. The timer itself is not JavaScript and does not occupy the stack.
  3. console.log("two") runs. The script ends, and the call stack is empty.
  4. Meanwhile the timer has expired, so the browser has put a task for the callback into the .
  5. The sees an empty call stack, takes the task and runs it: three is logged.

So setTimeout(fn, 0) does not mean "run fn now". It means "queue fn as a new task once at least 0 ms have passed". The delay is a minimum, not a guarantee: if the current code keeps the thread busy for 200 ms, the callback waits at least that long.

The same pieces take part in every asynchronous operation:

PieceOwned byJob
Call stackJS engineRuns code, one frame at a time
Web APIsBrowserTimers, network, DOM events — work done outside your JavaScript
Task queueBrowserCallbacks waiting for their turn
Event loopBrowserRuns the next task whenever the call stack is empty

A click works the same way: the browser notices the click, queues a task that dispatches the event, and your click listener runs only when the stack is free. If your code is in the middle of a long loop, the click is not lost — it waits in the queue.

Strictly speaking, a browser has several task queues (for example, for timers and for user input) and decides which one to serve next. For now, picture a single queue processed in order.

JuniorExample

Worked example: tracing the order

JavaScript
console.log("A");

setTimeout(() => {
  console.log("B");
}, 0);

function heavy() {
  const end = Date.now() + 100;
  while (Date.now() < end) {}
  console.log("C");
}

heavy();
console.log("D");

The output is A, C, D, B — and B appears only after about 100 ms, even though its delay is 0.

Step by step:

  1. A is logged synchronously.
  2. setTimeout hands the callback to the browser's timer and returns. Nothing is queued yet.
  3. heavy() runs a busy loop for 100 ms. Almost immediately the timer expires and the browser puts the callback into the task queue — but the call stack is not empty, so the callback has to wait.
  4. heavy logs C and returns.
  5. The script logs D and finishes; the call stack is now empty.
  6. The event loop takes the waiting task and runs it: B.

The same trace as a table:

StepCall stackTask queueLogged
1script—A
2script → setTimeout——
3script → heavytimer callback—
4script → heavytimer callbackC
5scripttimer callbackD
6timer callback—B

What to take away

  • Synchronous code always finishes first. Callbacks queued by timers and events run later, one at a time.
  • A timer's delay is the earliest moment the callback may run, not the moment it will run.
  • Busy code delays everything. In a browser, the same 100 ms loop would also delay click handlers and screen updates: clicks made during the loop are handled only after D is logged.
MiddleWeb platform

Microtasks vs tasks

Besides the , every event loop has a single microtask queue. come from:

  • reactions — the callbacks passed to then, catch and finally;
  • the continuation of an async function after await;
  • queueMicrotask(fn);
  • MutationObserver callbacks.

Tasks (often called macrotasks) come from timers, user input, network events and postMessage, among others.

The rule

After every task, the browser performs a microtask checkpoint: it runs microtasks until the queue is empty — including microtasks queued while it is draining. Only then can the loop move on to rendering or to the next task. A checkpoint also happens whenever the call stack becomes empty after a callback, for example between two event listeners during a real user click.

JavaScript
setTimeout(() => console.log("task"), 0);
Promise.resolve().then(() => console.log("microtask 1"));
queueMicrotask(() => console.log("microtask 2"));
console.log("sync");

Output: sync, microtask 1, microtask 2, task. Both microtasks run as soon as the script finishes; the timer callback waits for the next task turn.

Where async/await fits

is syntax on top of promises. The code before the first await runs synchronously; the rest of the function resumes as a microtask once the awaited value settles:

JavaScript
async function save() {
  console.log("before");
  await write();
  console.log("after");
}

behaves roughly like:

JavaScript
function save() {
  console.log("before");
  return Promise.resolve(write()).then(() => {
    console.log("after");
  });
}

That is why await on a value that is already available — even await null — still pauses the function until the current synchronous code has finished.

Who defines what

The ECMAScript spec defines promise jobs but no event loop. The host defines the loop: in browsers, the HTML spec runs promise jobs as microtasks. Node.js has its own loop, but promise callbacks follow the same order relative to each other.

MiddleWeb platform

Where rendering fits: frames and requestAnimationFrame

The browser does not render after every task. It renders when it has a rendering opportunity — typically in step with the display's refresh rate (on a 60 Hz screen, at most about every 16.7 ms), less often if the page can't keep up, and much less often or not at all in a hidden tab. Then the event loop runs an "update the rendering" step between tasks. Simplified, it:

  1. fires resize and scroll events;
  2. runs callbacks;
  3. recalculates styles and runs ;
  4. and presents the new frame.

Three consequences follow.

Nothing is drawn in the middle of a task or while microtasks drain. All DOM changes made in one task appear together:

JavaScript
box.style.display = "block";
box.style.display = "none";

The user never sees the box, because no rendering can happen between these two lines.

Visual updates belong in requestAnimationFrame. A setTimeout loop is not aligned with frames: a callback may run twice between two frames (wasted work) or miss a frame (visible jank). requestAnimationFrame runs once per frame, right before style and layout, and passes a timestamp the animation can be based on:

JavaScript
function step(timestamp) {
  box.style.transform = `translateX(${(timestamp / 10) % 300}px)`;
  requestAnimationFrame(step);
}
requestAnimationFrame(step);

Long tasks block input and paint. While a task runs on the , the browser can neither run a click handler nor show a new frame. A task that keeps the main thread busy for 50 ms or more counts as a long task in the browser's performance APIs. If a click handler takes 300 ms, the page can't show any visual response for at least 300 ms — the kind of delay the Core Web Vitals metric INP (Interaction to Next Paint) measures.

MiddlePitfalls

Common pitfalls

Microtask starvation

The checkpoint drains the queue until it is empty, so a microtask that keeps queuing microtasks never lets the loop move on:

JavaScript
function loop() {
  queueMicrotask(loop);
}
loop();

The page freezes: no timers, no input handling, no rendering. A recursive promise chain does the same. The setTimeout version does not freeze the page, because each callback is a separate task and the browser can render and handle input between them.

Promises don't make code non-blocking

Wrapping heavy work in a promise does not move it off the main thread. The executor of new Promise(...) runs synchronously, and a then callback runs as a microtask — still before the next render. To stay responsive, split the work across tasks or move it to a Web Worker (see the Senior level).

Timers are not precise

  • The delay is a minimum; a busy main thread postpones every timer.
  • The HTML spec clamps nested timers: once setTimeout calls are nested more than five levels deep, delays below 4 ms become 4 ms.
  • Browsers throttle timers in background tabs, and the exact rules differ between browsers.

Use requestAnimationFrame for animations and performance.now() to measure elapsed time instead of counting callbacks.

Lost rejections

JavaScript
async function init() {
  try {
    loadConfig();
  } catch (error) {
    showError(error);
  }
}

If loadConfig is async, the missing await means catch never sees its rejection. When a promise is rejected without a handler, the browser checks it after the microtask checkpoint and, if it is still unhandled, fires an unhandledrejection event on window in a later task. In Node.js (since v15) an unhandled rejection crashes the process by default. Attach catch (or await inside try) in the same synchronous code that creates the promise.

SeniorFramework

React and the event loop

Automatic batching

Calling a set function does not re-render immediately — it queues an update. React waits until the code that queued the updates (an event handler, for example) has finished, and then processes them together in one render. Since React 18 with createRoot, this applies wherever the updates come from: React event handlers, setTimeout, promises or native event listeners.

TSX
function handleClick() {
  fetchUser().then((user) => {
    setUser(user);
    setLoading(false);
  });
}

Both updates produce a single re-render. React does not batch across separate intentional events, though: two clicks are handled separately. Also note that reading state right after calling its setter still gives the old value, because the new value only exists in the next render.

flushSync: the escape hatch

Sometimes the DOM has to be up to date before the next line runs — for example, to scroll to an item you have just added:

TSX
import { flushSync } from "react-dom";

function handleAdd(text: string) {
  flushSync(() => {
    setTodos((prev) => [...prev, text]);
  });
  listRef.current?.lastElementChild?.scrollIntoView();
}

flushSync forces React to process the updates and update the DOM synchronously. react.dev calls it uncommon and warns that it can significantly hurt performance and may force Suspense boundaries to show their fallback.

Effects and paint

The browser paints only in its rendering step, after the current JavaScript has finished. That explains the difference between the two effect hooks:

  • useLayoutEffect runs after React commits to the DOM and before the browser repaints. Its code and any state updates scheduled from it block the paint, so you can measure an element and reposition it without a visible flicker. Overusing it makes the app slow.
  • useEffect: if the Effect was not caused by an interaction, React generally lets the browser paint first. If it was caused by an interaction such as a click, React may run it before paint. To defer work until after paint (for example, an alert()), react.dev suggests setTimeout.
SeniorWeb platform

Scheduling long work, React's scheduler and Node.js

Yield to the event loop

Nothing can interrupt a running task, so the only way to stay responsive during heavy work is to stop voluntarily and continue in a new task. Yielding with a microtask (await Promise.resolve()) does not help: rendering and input wait until the microtask queue is empty.

JavaScript
function yieldToMain() {
  if (globalThis.scheduler?.yield) {
    return scheduler.yield();
  }
  return new Promise((resolve) => setTimeout(resolve, 0));
}

async function processAll(items, handleItem) {
  let sliceStart = performance.now();
  for (const item of items) {
    handleItem(item);
    if (performance.now() - sliceStart > 10) {
      await yieldToMain();
      sliceStart = performance.now();
    }
  }
}

scheduler.yield() schedules the continuation as a prioritized task, but MDN lists it as limited availability, so feature-detect it. Keep each slice well under the 50 ms long-task threshold. CPU-heavy work that can't be split sensibly belongs in a Web Worker, which has its own thread and event loop.

React's scheduler

React applies the same idea. Its scheduler package runs work as macrotasks — in browsers through MessageChannel, which, unlike nested setTimeout, is not clamped to 4 ms. During concurrent rendering (startTransition, useDeferredValue), React checks between units of work whether its time slice of a few milliseconds is used up and, if so, yields and continues in a new task. A transition render can also be interrupted by a more urgent update such as typing. The commit to the DOM is not split.

Node.js differences

  • The loop is implemented by libuv and runs in phases: timers → pending callbacks → poll (I/O) → check (setImmediate) → close callbacks.
  • process.nextTick callbacks have their own queue. In CommonJS code and inside callbacks it is drained before promise microtasks; in the top-level code of an ES module, promise callbacks run first. Node's docs recommend queueMicrotask unless you need nextTick specifically.
  • From the main module, the order of setTimeout(fn, 0) and setImmediate(fn) is non-deterministic; inside an I/O callback, setImmediate always runs first.
  • Recursive nextTick calls starve I/O, just as recursive microtasks freeze a page.
SeniorInterview tips

Interview tips

Structure the explanation

Build the answer bottom-up: one thread and a → the host does asynchronous work through Web APIs → finished work is queued as tasks → after each task the microtask queue is drained → the browser renders when it has a rendering opportunity. Mentioning that ECMAScript defines promise jobs while the HTML spec defines the event loop shows depth.

Tracing output questions

Keep three columns: output, microtask queue, task queue.

  1. Run all synchronous code and note what each line queues.
  2. Drain the microtask queue front to back. Anything queued meanwhile goes to the end and runs in the same pass.
  3. Run one task, then drain the microtasks again. Repeat.

Watch for the classic traps: code before the first await is synchronous; then on an already-resolved promise is queued immediately, but a chained then is queued only when the previous callback finishes; every timer callback is its own task.

Details that stand out

  • With a real user click, microtasks run between two listeners on the same element, because the call stack empties between them. With element.click() called from a script, the stack is not empty, so both listeners run first and the microtasks after them.
  • Connect the theory to practice: long tasks hurt INP, heavy work should yield between chunks, React batches updates, and useLayoutEffect blocks paint.

Misconceptions to avoid

  • "setTimeout(fn, 0) runs immediately."
  • "Promises run on another thread."
  • "async makes a function run in parallel."
  • "The browser repaints after every task."
JuniorReview checklist

What to check when reviewing code for event loop issues

Use this list when you review code you did not write: a teammate's pull request, a snippet from a library's issue tracker or a suggestion from an AI assistant. Skip it and the code can block the , so clicks and repaints wait, or lose errors and run callbacks in an order nobody planned.

  • Does a handler or loop do heavy work in one go? While a task runs, the browser can neither handle a click nor paint. Record it in the DevTools Performance panel, which marks long tasks with a red triangle; expect chunks that yield with setTimeout or scheduler.yield(), or a Web Worker.
  • Does the code assume that a promise or async moves work off the thread? The new Promise executor runs synchronously, and then callbacks run as before the next render, so await Promise.resolve() lets neither paint nor input through.
  • Is every async call inside try awaited? Without await, catch never sees the rejection: the browser fires unhandledrejection, and Node.js (since v15) ends the process by default.
  • Can a microtask queue itself again? A queueMicrotask or promise chain that keeps rescheduling itself never lets the loop reach timers, input or rendering, and the page freezes. Repeating work belongs in setTimeout, which lets the browser render in between.
  • Does the code rely on a timer's exact delay? The delay is a minimum: a busy thread postpones the callback, and background tabs throttle timers. Measure elapsed time with performance.now(), not by counting callbacks.
  • Do animations use requestAnimationFrame? Timer loops are not aligned with frames: they can run twice between frames or miss one. runs once per frame, right before style and layout.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    4 predict-output · 4 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    6 questions

Hands-on work that uses this topic.

Guided tours through the source of real libraries that rely on it.