Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

One, the introduction

As we all know, most of the applications we use are event-driven. When we interact with the application, there will be many events, such as click, double click, triple click, etc., and many events will be generated during the completion of file reading or the execution of certain tasks.

We all know that Node.js is single-process, single-threaded, but can achieve high concurrency because of our event mechanism. In particular, it is implemented through event loops, with asynchronous callback interfaces and event drivers enabling high concurrency.

Second, the event cycle

In the Node. Js single-threaded runtime, equivalent to enter a “dead” cycle, on each asynchronous event callback function is equivalent to check your phone’s girlfriend, if your girlfriend found something “bad” (event), and you quarrel quarrel (callback function called – function), until later all didn’t see the the things that make you fight (events), Stop checking your phone.

The event loop also typically hands off the operations to the operating system, and we all know that today’s operating systems are mostly multithreaded. That means we know that node.js doesn’t just look at our phones, she hires a team of professional monitors to monitor yours. This allows you to monitor multiple people on your team to check your phone messages (processed in the background by the operating system) and notify your girlfriend as soon as a part of the message is processed (an operation has been completed, Notify Node.js immediately), and the girlfriend will queue the task based on the nature of the message (Node.js will add the relevant callback function to the polling queue) and execute it one by one.

Here’s a simplified graph of the Node.js event loop:

In the diagram above, each stage will have a FIFO queue of the callback function, usually when the event loop to enter one of the stage, will perform the phase of the operation, to carry out the stage in the queue callback, till the end of the queue or reach the limit of callback number, after the event loop will enter the next phase, this cycle back and forth.

According to this graph, we can know that the order of the event cycle is approximately:

Incoming data -> poll -> Check -> Close callback -> Timers -> Pending callbacks -> Idle, incoming data -> poll -> Check -> Close callback -> Timers -> Pending callbacks -> Idle Prepare) – > polling (poll)