Skip to the page

The event loop · core

The event loop, step by step

The event loop repeats one cycle: take the oldest task from a task queue and run it to completion, then run every microtask until the microtask queue is empty, then let the browser render if a frame is due — and start again.

The notes

What you must know

  • Parts: the call stack; the host APIs (timers, network, DOM events); task queues (macrotasks); one microtask queue; and the rendering steps.
  • One cycle: run one task -> drain ALL microtasks, including microtasks added while draining -> maybe render (requestAnimationFrame callbacks, style, layout, paint) -> next task.
  • Running the main script is itself a task. Each event handler and each timer callback is a task.
  • Task sources: setTimeout, setInterval, UI events, MessageChannel, network callbacks (and setImmediate and I/O in Node). Microtask sources: promise reactions (then, catch, finally), await continuations, queueMicrotask, MutationObserver.
  • Rendering never happens in the middle of a task or between microtasks. At 60 Hz the browser renders about every 16.7 ms, and only if something changed.
  • The browser has many threads (network, compositor, raster, workers), but your page's JavaScript runs on the main thread.
  • Timer delays are minimums: the callback waits for the stack and microtasks, nested timers are clamped to about 4 ms after 5 levels, and background tabs throttle timers.

The red pen

Common traps: mistake → fix

  • Mistake: There is one queue

    Fix: there are task queues, a separate microtask queue, and separate rendering steps.

  • Mistake: Promises have 'higher priority'

    Fix: say it precisely: all microtasks drain after every task, before rendering and before the next task.

  • Mistake: setTimeout(fn, 100) runs at exactly 100 ms

    Fix: at least 100 ms, and only when the stack and microtask queue are empty.

Easy to hard

Questions interviewers ask, easy to hard

  1. Explain the event loop.
  2. What is a task vs a microtask? Give two examples of each.
  3. Where does rendering fit in the loop?
  4. What happens if a microtask keeps scheduling more microtasks?
  5. How is 'multithreading' achieved in JavaScript? (Flipkart 2025) Why does the main thread matter for INP?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview