In this lesson, you followed a small laundry-room program through a picture of what Node does behind the scenes, and saw why a timer that’s due waits while JavaScript is busy.
Key Points
- The picture has three places. The call stack holds the functions running right now, each on top of the one that called it. When you run a file, the script itself is the first thing on the stack.
- When your code calls
setTimeout(), Node starts a timer and keeps the callback in the waiting area. The waiting area is Node’s, outside your code, so the script carries on at once. - When a timer is due, its callback is ready to run. The picture shows that by moving it to the task queue. A task is a ready callback, waiting its turn. Tasks line up in the order their timers came due, not the order the script scheduled them.
- The event loop takes the first task from the queue and puts it on the stack. It runs on the same thread as your code, so it only gets a turn when the call stack is empty. Until then, nothing interrupts the code that’s running.
- This is the picture behind now and later. The script on the stack is now, and every callback still waiting, in the waiting area or the task queue, is later. Later starts only when the script finishes and leaves the stack empty.
- Run to completion means that once code starts, the script or a task, it runs to its end before the next task starts.
- That’s why a delay is a minimum, not a promise. Wren’s washer was due at one tenth of a second, but her line printed at three tenths, once the stack was empty.
- When the queue and the waiting area are both empty, Node ends the program.
- The picture is a model. In Node, the loop checks which timers are due when it gets its turn. The picture moves them into the queue early, to show they’re ready. For timers, the order is the same.
The rule: a timer callback runs only when the event loop moves it from the task queue onto an empty call stack.