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:
- Your code runs to completion on the call stack.
- Slow things (timers, file reads, network calls) are handed to Node's internals, which wait outside the thread.
- When a slow thing finishes, its callback is placed in the callback queue.
- 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.
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.