The Event Loop

Updated · 10 min read
hardES2026javascriptevent-loopmicrotasksasyncinterview

The event loop is the mechanism that lets single-threaded JavaScript handle many things "at once". The runtime keeps queues of work that is ready to run (a timer that fired, a click, a resolved promise), and the event loop repeatedly takes the next piece of work and runs it on the call stack to completion, then the next. There are two main queues with different priorities: the task queue (timers, events, I/O) and the microtask queue (promise reactions). Knowing how they interact explains every "what order does this print?" puzzle and many real bugs.

In One Minute

  • Call stack: where code runs. One function at a time; each runs to completion.
  • Task queue (macrotasks): timer callbacks, events, network and I/O callbacks. One task per loop turn.
  • Microtask queue: promise then/catch/finally callbacks, await continuations, queueMicrotask. All microtasks run after each task, before anything else.
  • In browsers, rendering happens between tasks, after microtasks, roughly every 16 ms.
  • Order rule: synchronous code first, then all microtasks, then the next task.

The Pieces

PartHoldsRun when
Call stackThe function running now, and its callersContinuously
Web APIs / Node.js APIsTimers counting down, requests in flight, listeners waitingIn the background, outside JavaScript
Task queueCallbacks whose event happened (timer fired, click, response arrived)One per turn, when the stack is empty
Microtask queuePromise reactions, queueMicrotask callbacksRight after the current task, until the queue is empty
Rendering (browsers)Style, layout, paint, requestAnimationFrame callbacksBetween tasks, when the browser decides to update the screen

One Turn of the Loop

The event loop repeats these steps:

  1. Take the oldest task from the task queue and run it until the call stack is empty.
  2. Run every microtask in the microtask queue, including microtasks added while running microtasks.
  3. If it's time to update the screen (browsers): run requestAnimationFrame callbacks, then calculate styles and layout, and paint.
  4. Go back to step 1.

Running your script for the first time counts as the first task.

Puzzle 1: Timer vs Promise

puzzle1.js▶ Try it
console.log("1. sync start");
 
setTimeout(() => console.log("5. timeout (task)"), 0);
 
Promise.resolve().then(() => console.log("3. promise (microtask)"));
 
queueMicrotask(() => console.log("4. queueMicrotask (microtask)"));
 
console.log("2. sync end");
Output
1. sync start
2. sync end
3. promise (microtask)
4. queueMicrotask (microtask)
5. timeout (task)

Step by step:

StepRunningMicrotask queueTask queue
Script runslogs 1; schedules timer; queues promise reaction; queues microtask; logs 2promise, microtasktimeout
Script ends (stack empty)run all microtasks: logs 3, logs 4(empty)timeout
Next tasktimeout callback: logs 5

Even with a delay of 0, the timer callback is a task, so it waits until the current task (the script) and all microtasks are done.

Puzzle 2: Microtasks Inside Tasks

puzzle2.js▶ Try it
setTimeout(() => {
  console.log("A: timer 1");
  Promise.resolve().then(() => console.log("B: microtask from timer 1"));
}, 0);
 
setTimeout(() => console.log("C: timer 2"), 0);
 
Promise.resolve().then(() => {
  console.log("D: microtask from script");
  setTimeout(() => console.log("E: timer from microtask"), 0);
});
Output
D: microtask from script
A: timer 1
B: microtask from timer 1
C: timer 2
E: timer from microtask

Explanation: after the script, the microtask D runs and schedules timer E (added to the end of the task queue, after timers 1 and 2). Then timer 1 runs as a task; its microtask B runs immediately after it, before timer 2, because microtasks drain after every task. Then timer 2, then timer E.

Puzzle 3: async/await

An await pauses an async function; the rest of the function (its continuation) is scheduled as a microtask when the awaited promise settles:

puzzle3.js▶ Try it
async function loadPayments() {
  console.log("2. loadPayments starts (synchronously)");
  await null;
  console.log("4. after await (microtask)");
  return [120, 85];
}
 
console.log("1. script start");
loadPayments().then((p) => console.log("5. then:", p.length, "payments"));
console.log("3. script continues");
Output
1. script start
2. loadPayments starts (synchronously)
3. script continues
4. after await (microtask)
5. then: 2 payments

Explanation: calling an async function runs its body synchronously up to the first await. At await, the function pauses and returns a pending promise to the caller, which continues ("3"). When the stack empties, the continuation runs as a microtask ("4"), the function's promise resolves, and the then callback is queued as another microtask ("5").

Starvation: Microtasks Can Block Too

Because the microtask queue must be empty before the loop moves on, a microtask that keeps scheduling more microtasks blocks timers, events and rendering, just like a busy loop:

starvation.js▶ Try it
let count = 0;
const started = Date.now();
setTimeout(() => console.log(`timer finally ran after ${count} microtasks`), 0);
 
function spin() {
  count++;
  if (count < 100_000) queueMicrotask(spin);
}
queueMicrotask(spin);
Output
timer finally ran after 100000 microtasks

The timer had to wait for all 100,000 microtasks. With an endless chain, it would never run and a browser tab would freeze. Tasks don't have this problem: after each task, the loop gives other tasks (and rendering) a turn.

Rendering and requestAnimationFrame

In browsers, the screen can only update between tasks. Changing the DOM many times inside one task produces one paint at the end, and a long task delays painting entirely:

render.html
<p id="status">Start</p>
<script>
  const status = document.querySelector("#status");
  const log = [];
  let rafSaw = "";

  requestAnimationFrame(() => { rafSaw = status.textContent; });
  setTimeout(() => log.push("timeout task"), 0);
  Promise.resolve().then(() => log.push("microtask"));

  status.textContent = "Step 1";
  status.textContent = "Step 2";
  log.push("sync done");

  setTimeout(() => {
    console.log(log.join(" | "));
    console.log("rAF, just before the paint, saw:", rafSaw);
  }, 150);
</script>
Output
sync done | microtask | timeout task
rAF, just before the paint, saw: Step 2

The two DOM changes happened in the same task, so the screen never showed "Step 1": by the time requestAnimationFrame ran, just before the paint, the text was already "Step 2". Whether that paint comes before or after the zero-delay timer depends on the screen's refresh timing, so code must never rely on the order of requestAnimationFrame relative to timers.

Node.js Differences

Node.js has the same core model (call stack, tasks, microtasks) with a few extra queues, covered in the Node.js add-on:

Node.jsRuns
process.nextTick(fn)Before promise microtasks: the highest priority
Promise microtasksAfter nextTick callbacks
Timers phasesetTimeout, setInterval
Poll phaseI/O callbacks (files, network)
Check phasesetImmediate
node-order.js▶ Try it
setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
Promise.resolve().then(() => console.log("promise"));
process.nextTick(() => console.log("nextTick"));
console.log("sync");
Output
sync
nextTick
promise
timeout
immediate

The order of timeout and immediate from the main script can vary between runs (it depends on how quickly the event loop starts), which is why this output isn't compared word for word. Inside an I/O callback, setImmediate always runs first.

In Practice

The Fee Tracker processes 50,000 imported payment rows without freezing the page, by working in chunks and yielding to the event loop with a task between chunks, so clicks and rendering get a turn:

chunks.js▶ Try it
const rows = Array.from({ length: 50_000 }, (_, i) => ({ amount: (i % 450) + 1 }));
const yieldToEventLoop = () => new Promise((resolve) => setTimeout(resolve, 0));
 
let ticks = 0;
const ticker = setInterval(() => ticks++, 0);
 
let total = 0;
for (let start = 0; start < rows.length; start += 10_000) {
  for (const row of rows.slice(start, start + 10_000)) total += row.amount;
  await yieldToEventLoop();
}
clearInterval(ticker);
 
console.log("total:", total);
console.log("other tasks ran between chunks:", ticks > 0);
Output
total: 11265000
other tasks ran between chunks: true

Between chunks, the interval timer (standing in for clicks and rendering) got to run. Without the await yieldToEventLoop(), it couldn't have run until all the work was done.

Common Mistakes

Assuming setTimeout(fn, 0) runs immediately. It runs after the current code and all microtasks.

Expecting promise callbacks to run synchronously. then callbacks are always asynchronous, even for already-resolved promises.

Breaking up work with microtasks. They don't let rendering or input happen. Yield with a task.

Long synchronous tasks. Anything over about 50 ms makes the page feel sluggish. Split work, or move it to a Web Worker.

Under the Hood

The event loop isn't part of ECMAScript itself. The language specification defines jobs (its name for microtasks: promise reactions are "PromiseJobs") and leaves scheduling to the host. Browsers implement the event loop as defined in the HTML Standard: each event loop has one or more task queues (the browser may prioritize between them, for example user input over timers), a microtask queue, and a "microtask checkpoint" performed after each task and after each callback invoked from rendering. Node.js uses libuv, a C library, whose loop runs in phases (timers, pending callbacks, poll, check, close), draining the nextTick queue and then V8's microtask queue between every callback. In both, the essential guarantee is the same: a piece of JavaScript is never interrupted by another piece of JavaScript on the same thread, which is why you don't need locks for ordinary variables, and why long-running code freezes everything.

Interview Corner

Explain the event loop.

JavaScript executes on a single call stack. Asynchronous operations are handled by the host (browser or Node.js), which queues callbacks as tasks when they complete. The event loop takes one task at a time, runs it to completion, then drains the microtask queue (promise reactions, await continuations, queueMicrotask), then in browsers may render, and repeats. Hence sync code runs first, then all microtasks, then the next task.

What is the difference between microtasks and macrotasks?

Macrotasks (tasks) include timers, I/O, UI events and message events; one runs per loop iteration. Microtasks include promise callbacks and queueMicrotask; the entire microtask queue is drained after each task, including microtasks queued during draining. So microtasks always run before the next timer or event, and an endless chain of microtasks starves rendering and input.

What does this print?

Show solution
puzzle.js▶ Try it
console.log("a");
setTimeout(() => console.log("b"), 0);
(async () => {
  console.log("c");
  await undefined;
  console.log("d");
})();
Promise.resolve().then(() => console.log("e"));
console.log("f");
Output
a
c
f
d
e
b

"c" runs synchronously inside the async function. The await continuation ("d") was queued before the then callback ("e"), so it runs first. The timer ("b") is a task, so it runs last.

Practice

Challenge: Predict the output, then run it: a setTimeout logging "T", a queueMicrotask logging "M1" that itself queues a microtask logging "M2", and a synchronous log "S".

Show solution
predict.js▶ Try it
setTimeout(() => console.log("T"), 0);
queueMicrotask(() => {
  console.log("M1");
  queueMicrotask(() => console.log("M2"));
});
console.log("S");
Output
S
M1
M2
T

Quick check: The event loop

3 questions
1What runs first after a script finishes?
2Which of these is a microtask?
3Why can an endless chain of microtasks freeze a page?

Key Takeaways

CodeQueue
setTimeout, setIntervalTask
Event listeners, I/O callbacksTask
promise.then/catch/finally, after awaitMicrotask
queueMicrotask(fn)Microtask
requestAnimationFrameBefore the next paint (browsers)
process.nextTickBefore promise microtasks (Node.js)

Was this tutorial helpful?

Lesson 102 of 139