Understanding the event loop
The following three points are important to remember, as we break down the event loop:
- The event loop runs in the same (single) thread your JavaScript code runs in. Blocking the event loop means blocking the entire thread.
- You don't start and/or stop the event loop. The event loop starts as soon as a process starts, and ends when no further callbacks remain to be performed. The event loop may, therefore, run forever.
- The event loop delegates many I/O operations to
libuv
, which manages these operations (using the power of the OS itself, such as thread pools), notifying the event loop when results are available. An easy-to-reason-about single-threaded programming model is reinforced with the efficiency of multithreading.
For example, the following while
loop will never terminate:
let stop = false; setTimeout(() => { stop = true; }, 1000); while (stop === false) {};
Even though one might expect, in approximately one second, the assignment of a Boolean true
to the...