Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Notes › JavaScript

The JavaScript Event Loop

JavaScript runs on one thread — it does one thing at a time. Yet it handles timers, network requests and clicks without freezing. The event loop makes that possible.

The pieces

Piece What it does
Call stack runs functions one at a time (last in, first out)
Web APIs / Node APIs the browser or Node does the waiting: timers, fetch, DOM events, file I/O
Macrotask (task) queue callbacks from setTimeout, setInterval, I/O, UI events
Microtask queue promise callbacks (.then, await continuation), queueMicrotask, MutationObserver
Event loop when the stack is empty, runs all microtasks, then one macrotask, then repeats

The rule that solves every output question

  1. Run the current synchronous code until the call stack is empty.
  2. Run every microtask (including new ones added meanwhile).
  3. Render (in the browser), then take one macrotask and go back to step 1.
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");
// Output: 1, 4, 3, 2

async/await is promises

Code after await is put in the microtask queue.

async function f() {
  console.log("A");
  await null;            // pause: the rest becomes a microtask
  console.log("B");
}
console.log("start");
f();
console.log("end");
// start, A, end, B

Details of promises: JavaScript Promises & Async/Await.

A harder puzzle

setTimeout(() => console.log("t1"), 0);
Promise.resolve()
  .then(() => {
    console.log("p1");
    setTimeout(() => console.log("t2"), 0);
  })
  .then(() => console.log("p2"));
queueMicrotask(() => console.log("m1"));
console.log("sync");

Output: sync, p1, m1, p2, t1, t2

setTimeout delay is a minimum

setTimeout(fn, 100) means "not before 100 ms". If the stack is busy (a long loop), the callback waits longer.

Blocking the event loop

const start = Date.now();
while (Date.now() - start < 3000) {}   // 3 s of busy work freezes clicks, rendering, timers

Fixes: split heavy work into chunks (setTimeout), use a Web Worker (browser) or worker_threads (Node), or move CPU work to the server.

Node.js event loop phases (overview)

timers → pending callbacks → poll (I/O) → check (setImmediate) → close callbacks. Between phases Node runs microtasks; process.nextTick callbacks run even before promise microtasks.

setImmediate(() => console.log("immediate"));
process.nextTick(() => console.log("nextTick"));
Promise.resolve().then(() => console.log("promise"));
// nextTick, promise, immediate

Interview one-liners

More JavaScript notes