Analysis of the event loop in Node
This article introduces to you the analysis of the event loop in Node. It has certain reference value. Friends in need can refer to it.
Each stage in the event loop
The event loop process of Node.js is roughly as follows:
┌───────────────────────────┐ ┌─>│ timers │ │ └─────────────┬─────────────┘ │ ┌─────────────┴─────────────┐ │ │ pending callbacks │ │ └─────────────┬─────────────┘ │ ┌─────────────┴─────────────┐ │ │ idle, prepare │ │ └─────────────┬─────────────┘ ┌───────────────┐ │ ┌─────────────┴─────────────┐ │ incoming: │ │ │ poll │<─────┤ connections, │ │ └─────────────┬─────────────┘ │ data, etc. │ │ ┌─────────────┴─────────────┐ └───────────────┘ │ │ check │ │ └─────────────┬─────────────┘ │ ┌─────────────┴─────────────┐ └──┤ close callbacks │ └───────────────────────────┘
Each stage has its own task queue. When the task of this stage After all queues have been executed, or the maximum number of tasks executed has been reached, it will enter the next stage.
timers phase
This phase will execute the scheduled tasks set by setTimeout
and setInterval
.
Of course, this timing is not accurate, but after the timing time is exceeded, once the execution opportunity is obtained, it will be executed immediately.
pending callbacks stage
This stage will perform some operations related to the underlying system, such as errors returned by TCP connections, etc. When these errors occur, they will be postponed by Node to the next cycle.
Polling phase
This phase is used to execute callbacks related to IO operations. Node will ask the operating system whether a new IO event has been triggered, and then execute the corresponding event. callback. Almost all operations except timer events, setImmediate()
and close callbacks
will be performed during this phase.
check phase
This phase will execute the tasks set by setImmediate()
.
close callbacks phase
If a socket
or handle(handle)
is suddenly closed, for example through socket.destroy()
is closed, the close
event will be emitted at this stage.
Specific execution of the event loop
After the event loop is initialized, it will proceed according to the process shown in the figure above:
First, the timer will be executed in sequence Tasks in
pending callback
callback;and then enters the
idle
andprepare
stages, where Node will be executed Some internal logic;and then enters the
poll
polling phase. At this stage, all IO callbacks will be executed, such as reading files, network operations, etc. Thepoll
stage has apoll queue
task queue. The execution process of this stage is relatively long, as follows:
Entering this stage, it will first check whether the
timeout
timing queue is available. The executed task, if any, will jump to thetimer stage
for execution.If there is no
timer task
, thepoll queue
task queue will be checked. If it is not empty, all tasks will be traversed and executed until they are all The execution is completed or the maximum number of tasks that can be executed is reached.poll queue
After the task queue is executed, it will check whether there are tasks in thesetImmediate
task queue. If so, the event loop will transfer Go to the nextcheck
stage.If there is no
setImmediate
task, then Node will wait here for the arrival of new IO callbacks and execute them immediately.
Note: This waiting will not continue forever. Instead, after reaching a certain limit, it will continue to the next stage for execution.
setTimeout()
and setImmediate()
A little secret
It’s not actually a secret, but I’m I just found out after checking the information.
That is: in Node, setTimeout(callback, 0)
will be converted to setTimeout(callback, 1)
.
Please refer here for details.
setTimeout()
and setImmediate()
Execution order
The execution order of the following two scheduled tasks performs inconsistently under different circumstances. .
setTimeout(function() { console.log('timeout'); }, 0); setImmediate(function() { console.log('immediate'); });
Set the timer in ordinary code
If you set these two scheduled tasks in the ordinary code execution stage (for example, in the outermost code block), their execution order is different. stable.
First of all, the
setTimeout(callback, 0)
we set has been converted intosetTimeout(callback, 1)
, so enterTimer
During the stage, it will be judged based on the current time whether the timing exceeds1ms
.Before the event loop enters the timer phase, the system calls a method to update the current time. Since other programs are running in the system at the same time, the system needs to wait for the processes of other programs to end. Get the accurate time, so there may be a certain delay in updating the time.
When updating the time, if there is no delay, the timing is less than
1ms
,immediate
The task will be executed first; if there is a delay, and this time When the limit of1ms
is reached, thetimeout
task will be executed first.
Set the timer in the IO callback
If we set these two timers in the IO callback, then the setImmediate
task will first Executed for the following reasons:
进入
poll phase
轮询阶段之前会先检查是否有timer
定时任务。如果没有
timer
定时任务,才会执行后面的 IO 回调。我们在 IO 回调中设置
setTimeout
定时任务,这时已经过了timer
检查阶段,所以timer
定时任务会被推迟到下一个循环中执行。
process.nextTick()
无论在事件循环的哪个阶段,只要使用 process.nextTick()
添加了回调任务,Node 都会在进入下一阶段之前把 nextTickQueue
队列中的任务执行完。
setTimeout(function() { setImmediate(() => { console.log('immediate'); }); process.nextTick(() => { console.log('nextTick'); }); }, 0); // nextTick // immediate
上述代码中,总是先执行 nextTick
任务,就是因为在循环在进入下一个阶段之前会先执行 nextTickQueue
中的任务。下面代码的执行结果也符合预期。
setImmediate(() => { setTimeout(() => { console.log('timeout'); }, 0); process.nextTick(() => { console.log('nextTick'); }); }); // nextTick // timeout
相关推荐:
The above is the detailed content of Analysis of the event loop in Node. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
