An overview of the
In both the browser environment and the Node environment, the event loop running js is the most important, but the two environments are based on different principles, especially before node.js 10+ version, one is based on the browser, the other is based on the Libuv library.
Event loop
The event loop is an infinite while-true loop.
Six stages
The event cycle is divided into six stages:
- Timers: Executes setTimout and setInterval callbacks.
- Pending Callbacks: Callbacks that perform certain system operations, such as TCP error types;
- Prepare: internal use of the system;
- Poll: Performs I/ O-related callbacks, during which the Node may block. All event loops and callback processing are performed here;
- Check: setImmediate() callback executes here. Instead of performing right away, setImmediate executes that part of the poll when there are no new events to handle;
Initiate an event loop
When node.js is started, it initializes the event loop and processes the input script provided. It may call some asynchronous API, schedule timer, or process.nexttick () before processing the event loop.
So, node.js event loops originate from four points:
- After node.js is started;
- SetTimeout callback;
- SetInterval callback;
- It could also be a callback function after an I/O.