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:

  1. Timers: Executes setTimout and setInterval callbacks.
  2. Pending Callbacks: Callbacks that perform certain system operations, such as TCP error types;
  3. Prepare: internal use of the system;
  4. Poll: Performs I/ O-related callbacks, during which the Node may block. All event loops and callback processing are performed here;
  5. 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:

  1. After node.js is started;
  2. SetTimeout callback;
  3. SetInterval callback;
  4. It could also be a callback function after an I/O.

Execute the process