SyntaxPilot
Courses/JavaScript/Lesson 24
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

JavaScript · Lesson 24 of 40

The event loop

queued

These are the notes for JavaScript episode 24. JavaScript runs your code on one thread, one line at a time. So what happens when it has to wait? A "wait 2 seconds" written as a busy while loop freezes the whole program: a ticker that should print every 500 ms prints nothing until the wait is over. You'll see why (one thread, one call stack, and nothing else can run while it's busy), overflow the stack on purpose (RangeError: Maximum call stack size exceeded), and then invent the fix: let Node.js or the browser do the waiting, put finished callbacks in a task queue, and run them with an event loop whenever the stack is empty. That explains why setTimeout(fn, 0) runs after your code, why promises (microtasks) jump ahead of timers, why a timer can fire late, and the var + setTimeout loop trap. Every output below is real Node.js output (node main.js); timings will differ slightly on your machine.

Builds on: functions and arrow functions (episode 9), scope and closures (10), try/catch (13), Date.now() (20). Leads to: callbacks (25), promises (26), async/await (27).

The real-life idea: the one-person chai stall

A railway-station chai stall has a long queue and one chaiwala.

  • The new chaiwala puts the tea on and stares at the pot for three minutes. Nobody else is served: the whole queue is stuck.
  • The experienced chaiwala puts the pot on and takes the next order. The stove does the waiting. When the bell rings, the ready tea waits on the counter until he's free, then he pours it.
Chai stall JavaScript
The one chaiwala the single thread and its call stack
Staring at the pot a blocking busy loop
The stove that does the waiting Node.js / the browser: timers, files, network (outside your JavaScript)
Ready cups waiting on the counter the task queue (callbacks ready to run)
"Free? Pour the next cup!" the event loop
A VIP who's served first the microtask queue (promises)

The problem: waiting freezes everything

function wait(ms) {
  const end = Date.now() + ms;
  while (Date.now() < end) {}
}
const start = Date.now();
const timer = setInterval(() => console.log("tick", Date.now() - start, "ms"), 500);
console.log("Boiling tea...");
wait(2000);
console.log("Tea ready at", Date.now() - start, "ms");
setTimeout(() => clearInterval(timer), 1100);
Boiling tea...
Tea ready at 2002 ms
tick 2002 ms
tick 2502 ms
tick 3002 ms
  • setInterval(fn, ms) runs fn again and again, every ms milliseconds, until clearInterval(id).
  • setTimeout(fn, ms) runs fn once, after at least ms milliseconds.

The ticks at 500, 1000 and 1500 ms never happened, and the missed ones were not "caught up". On a web page that's a frozen screen; on a server, every user waits.

Why: one thread, one call stack

A thread is one worker that runs code, one instruction at a time. JavaScript gives your code one thread. It tracks what it's doing on the call stack: when you call a function it's pushed on top; when it returns it's popped off. While anything is on the stack, nothing else can run: not a timer callback, not a click handler.

wait(2000) sat on the stack for two seconds, so the ticker's callbacks couldn't run.

The stack is real (and has a limit)

let depth = 0;
function brew() {
  depth++;
  brew();
}
try {
  brew();
} catch (e) {
  console.log(e.name + ":", e.message);
  console.log("stack depth reached:", depth);
}
RangeError: Maximum call stack size exceeded
stack depth reached: 12557

Each brew() call is pushed and never popped, until the stack runs out of room: a stack overflow. The exact depth depends on the machine and Node version. The fix for real code is a base case: a condition where the function stops calling itself.

The fix: the event loop

  1. Your code runs on the call stack.
  2. setTimeout, setInterval, reading a file, a network request: JavaScript hands the waiting to Node.js (or the browser), which does it outside your JavaScript, and your code keeps going.
  3. When the wait is over, the callback (the function you passed) is put in the task queue.
  4. The event loop repeats forever: is the call stack empty? Then take the next task from the queue and run it.
            your code                     Node.js / browser
        ┌──────────────┐  setTimeout   ┌────────────────────┐
        │  call stack  │ ────────────▶ │ timers, files, net │
        └──────▲───────┘               └─────────┬──────────┘
               │ stack empty?                    │ done
               │                                 ▼
          event loop  ◀──────────────  task queue: [cb, cb, ...]

setTimeout 0 runs later

console.log("A: take order");
setTimeout(() => console.log("B: tea is ready"), 0);
console.log("C: take next order");
A: take order
C: take next order
B: tea is ready

The 0 ms timer finishes immediately, but its callback waits in the queue until the stack is empty, which is after all of the main code.

Non-blocking waiting

const start = Date.now();
const timer = setInterval(() => console.log("tick", Date.now() - start, "ms"), 500);
console.log("Boiling tea...");
setTimeout(() => {
  console.log("Tea ready at", Date.now() - start, "ms");
  clearInterval(timer);
}, 2000);
console.log("Taking the next order");
Boiling tea...
Taking the next order
tick 501 ms
tick 1012 ms
tick 1513 ms
Tea ready at 2004 ms

Same two seconds, nothing froze. Code that hands waiting off instead of holding the stack is non-blocking (or asynchronous). The same is true for files:

const fs = require("fs");
console.log("1 before readFile");
fs.readFile(__filename, "utf8", (err, text) => {
  console.log("3 file read:", text.length, "characters");
});
console.log("2 after readFile");
1 before readFile
2 after readFile
3 file read: 204 characters

(The script reads its own file, __filename; the character count depends on the file.)

The VIP queue: microtasks

There are two queues:

  • Task queue (macrotasks): setTimeout, setInterval, I/O callbacks, setImmediate.
  • Microtask queue: promise reactions (.then, .catch, await, episodes 26–27) and queueMicrotask(fn).

Rule: every time the stack empties, the event loop runs all microtasks first, then one task, then all microtasks again, and so on.

console.log("1 sync");
setTimeout(() => console.log("2 timeout"), 0);
Promise.resolve().then(() => console.log("3 promise"));
queueMicrotask(() => console.log("4 microtask"));
console.log("5 sync");
1 sync
5 sync
3 promise
4 microtask
2 timeout

Node.js extras: process.nextTick and setImmediate

setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
process.nextTick(() => console.log("nextTick"));
Promise.resolve().then(() => console.log("promise"));
console.log("sync");
sync
nextTick
promise
timeout
immediate

process.nextTick runs before promise microtasks. In the main script the order of timeout and immediate can vary between runs (inside an I/O callback, setImmediate always comes first); don't write code that depends on it.

Common mistakes (and what really happens)

You wrote What happens Why Fix
while (Date.now() < end) {} to wait the program freezes; no ticks, no clicks it blocks the only call stack setTimeout(fn, ms)
function f() { return f(); } RangeError: Maximum call stack size exceeded the stack never empties add a base case
setTimeout(fn, 0) expecting it to run now runs after the current code (A, C, B) callbacks wait in the queue put code that must run now before it
setTimeout(fn, 100) then a 1.5 s loop 100 ms timer fired after 1503 ms the delay is a minimum keep the stack free; split heavy work
for (var i...) setTimeout(() => log(i)) 4 4 4 one shared var, read after the loop ends let (a new binding per round)
A huge calculation in one go on a server every request waits one thread split into chunks, or worker threads
const t = Date.now();
setTimeout(() => console.log("100 ms timer fired after", Date.now() - t, "ms"), 100);
const end = Date.now() + 1500;
while (Date.now() < end) {}
console.log("busy loop done at", Date.now() - t, "ms");
busy loop done at 1500 ms
100 ms timer fired after 1503 ms
for (var i = 1; i <= 3; i++) {
  setTimeout(() => console.log("var:", i), 0);
}
for (let j = 1; j <= 3; j++) {
  setTimeout(() => console.log("let:", j), 0);
}
var: 4
var: 4
var: 4
let: 1
let: 2
let: 3

Mini project: heavy work without freezing

Sum the numbers 1 to 30 million in chunks of 5 million, giving the event loop a turn between chunks so a "UI" ticker stays responsive:

const start = Date.now();
const ticker = setInterval(() => console.log("  [ui] still responsive at", Date.now() - start, "ms"), 100);
let total = 0;
let next = 1;
const LAST = 30_000_000;
function sumChunk() {
  const stop = Math.min(next + 5_000_000, LAST + 1);
  for (; next < stop; next++) total += next;
  console.log("summed up to", next - 1);
  if (next <= LAST) setTimeout(sumChunk, 0);
  else {
    console.log("total =", total);
    clearInterval(ticker);
  }
}
sumChunk();
summed up to 5000000
summed up to 10000000
  [ui] still responsive at 115 ms
summed up to 15000000
summed up to 20000000
  [ui] still responsive at 219 ms
summed up to 25000000
summed up to 30000000
total = 450000015000000

setTimeout(sumChunk, 0) ends the current task, lets queued callbacks (the ticker) run, then continues. (30_000_000 uses numeric separators: underscores just make big numbers readable.)

Practice

  1. Predict, then run: three logs, two timeouts and one promise.
  2. Make a countdown from 5 to 1, one number a second, then "Chai is ready!", without freezing the program.
  3. Measure how late a 50 ms timer fires behind a 1-second busy loop.
  4. Explain the event loop to a friend using the chai stall (no code!).
Solutions

1.

console.log("log 1");
setTimeout(() => console.log("timeout 1"), 0);
Promise.resolve().then(() => console.log("promise"));
setTimeout(() => console.log("timeout 2"), 0);
console.log("log 2");
console.log("log 3");
log 1
log 2
log 3
promise
timeout 1
timeout 2

2.

function countdown(n) {
  if (n === 0) {
    console.log("Chai is ready!");
    return;
  }
  console.log(n);
  setTimeout(() => countdown(n - 1), 1000);
}
countdown(5);
console.log("(the program is free while counting)");
5
(the program is free while counting)
4
3
2
1
Chai is ready!

This isn't a stack overflow: each countdown call returns before the next one starts from the queue.

3.

const t = Date.now();
setTimeout(() => console.log("50 ms timer fired after", Date.now() - t, "ms"), 50);
const end = Date.now() + 1000;
while (Date.now() < end) {}
50 ms timer fired after 1001 ms
  1. One chaiwala (one thread) does one thing at a time (the call stack). The stove does the waiting (Node.js/the browser). Ready cups wait on the counter (the task queue). Whenever he's free, he serves the next cup (the event loop). VIP orders (promises) are always served before the counter queue.

Quick quiz

In what order do these print?

setTimeout(() => console.log("X"), 0);
Promise.resolve().then(() => console.log("Y"));
console.log("Z");
  • A. Z Y X
  • B. X Y Z
  • C. Z X Y
  • D. Y Z X
Answer

A. Normal code first (Z), then the microtask queue (the promise, Y), then the task queue (the timer, X).

Interview questions

  • Is JavaScript single-threaded? How can Node.js handle thousands of connections?
  • What is the call stack? What causes "Maximum call stack size exceeded"?
  • What is the event loop? What does it check, and when does it run a callback?
  • Why does setTimeout(fn, 0) not run immediately?
  • What's the difference between the task (macrotask) queue and the microtask queue? Give examples of each.
  • Order these: sync code, setTimeout 0, Promise.then, process.nextTick.
  • Why is setTimeout's delay only a minimum?
  • What does "blocking the event loop" mean? How do you avoid it with heavy work?
  • Why does for (var i...) setTimeout(() => console.log(i)) print the same number?
  • Who actually waits for a timer or a file: JavaScript or the runtime?

Glossary

Term Meaning Example
Thread one worker that runs code, one instruction at a time JavaScript gives your code one
Single-threaded only one piece of your code runs at any moment JavaScript, Node.js
Call stack the pile of functions being run right now main → wait()
Push / pop put a call on top of the stack / take it off when it returns calling / returning
Stack overflow the stack ran out of room RangeError: Maximum call stack size exceeded
Base case the condition that stops a function calling itself if (n === 0) return;
Recursion a function calling itself brew() inside brew
Blocking code that holds the stack while it waits a busy while loop
Non-blocking / asynchronous starting a wait and carrying on; the result comes later setTimeout, fs.readFile
Busy wait waiting by looping and checking the clock while (Date.now() < end) {}
setTimeout(fn, ms) run fn once after at least ms ms setTimeout(cb, 2000)
setInterval(fn, ms) run fn every ms ms until cleared ticker
clearInterval(id) / clearTimeout(id) cancel an interval / a timeout clearInterval(timer)
Callback a function you hand over, to be called later () => console.log("B")
Runtime the program that runs your JavaScript and provides timers, files, network Node.js, a browser
Task queue (macrotask queue) where ready callbacks of timers and I/O wait timeout callbacks
Microtask queue a higher-priority queue for promise reactions .then callbacks
queueMicrotask(fn) put fn in the microtask queue runs before timers
Event loop the loop that runs the next queued callback whenever the stack is empty the chaiwala's "next cup!"
process.nextTick(fn) Node.js: run fn right after the current operation, before promises nextTick first
setImmediate(fn) Node.js: run fn in the "check" phase after I/O immediate
Numeric separator underscores in number literals for readability 30_000_000

Summary

  • JavaScript runs your code on one thread with one call stack; while the stack is busy, nothing else runs, so a busy wait freezes everything.
  • Waiting (timers, files, network) is done by Node.js or the browser; finished callbacks go into a queue.
  • The event loop runs the next queued callback only when the stack is empty, so setTimeout(fn, 0) runs after the current code.
  • Microtasks (promises, queueMicrotask) run before the next task (timers): sync → microtasks → tasks.
  • A timer's delay is a minimum. Keep the stack free: split heavy work, never busy-wait. Use let in loops with callbacks.

Next episode: Callbacks. The functions you hand to setTimeout and readFile have a name. How do you run steps in order with them, and why do they grow into a pyramid of doom?