The Event Loop
The event loop is the part of Node that runs waiting work. It takes each finished task and runs its callback in turn.
A timer waits
This timer prints Later after zero milliseconds. The main code still runs first.
setTimeout(() => {
console.log("Later");
}, 0);Main code runs first
This line runs at once, before any timer callback.
console.log("First");Example
console.log("First");
setTimeout(() => {
console.log("Later");
}, 0);
console.log("Second");Key points
- The event loop is a loop that keeps checking for finished work.
- A callback is a function that runs when its work finishes.
- A timer finishes after its delay, and the loop runs its callback.
- The loop runs one callback at a time.
- Main code runs first, and timer callbacks run after it.
- libuv is the library that watches timers and other waiting work for Node.
- A library is a set of ready code that a program uses.
In this example, the first print shows First at once. The timer waits zero milliseconds. The second print shows Second before the timer callback runs. The callback then prints Later last.
Note
A callback with a zero delay still runs after the main code.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What runs first, the main code or a timer callback?