Course outline · 0% complete

0/29 lessons0%

Course overview →

The Event Loop, Mapped

lesson 2-2 · ~9 min · 5/29

One thread, many requests

Node runs your JavaScript on a single thread: one line at a time, on one call stack (the pile of currently-running functions).

Understanding this machinery is not optional trivia: it explains why one slow piece of code can freeze every user of a Node server (a real and common production failure), and it is the single most asked Node interview topic.

So how does one thread serve thousands of users? With the event loop:

  1. Your code runs to completion on the call stack.
  2. Slow things (timers, file reads, network calls) are handed to Node's internals, which wait outside the thread.
  3. When a slow thing finishes, its callback is placed in the callback queue.
  4. Whenever the call stack is empty, the event loop takes the next callback from the queue and runs it.

That is the whole trick. Nothing ever interrupts running code, and no code ever waits idle on the thread.

Call stackyour code,one thing at a timeNode internalstimers, file reads,network waitsCallback queuefinished work lines up herehand off slow workevent loopstack empty?run next
The event loop cycle: slow work is handed off, finished callbacks queue up, and the loop feeds them back to the empty call stack.

Code exercise · javascript

Run this and match the output to the diagram: even a 0 ms timer must wait in the callback queue until the current code finishes.

Quiz

A request handler runs a loop that computes prime numbers for 10 full seconds. What happens to the other users of your server during that time?

Code exercise · javascript

Your turn. Without reordering the four statements, make the program print: sync 1, sync 2, timer A, timer B (each on its own line). You may only change the two delay numbers. Note timer B is scheduled first in the code but must print last.