Table of Contents
Each stage in the event loop
timers phase
pending callbacks stage
Polling phase
check phase
close callbacks phase
Specific execution of the event loop
setTimeout() and setImmediate()
A little secret
setTimeout() and setImmediate() Execution order
Set the timer in ordinary code
Set the timer in the IO callback
process.nextTick()
Home Web Front-end JS Tutorial Analysis of the event loop in Node

Analysis of the event loop in Node

Jul 20, 2018 am 10:30 AM
javascript node.js

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      │
   └───────────────────────────┘
Copy after login

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:

  1. First, the timer will be executed in sequence Tasks in pending callback callback;

  2. and then enters the idle and prepare stages, where Node will be executed Some internal logic;

  3. and then enters the poll polling phase. At this stage, all IO callbacks will be executed, such as reading files, network operations, etc. The poll stage has a poll 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 the timer stage for execution.

  • If there is no timer task, the poll 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 the setImmediate task queue. If so, the event loop will transfer Go to the next check 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(&#39;timeout&#39;);
}, 0);

setImmediate(function() {
    console.log(&#39;immediate&#39;);
});
Copy after login

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.

  1. First of all, the setTimeout(callback, 0) we set has been converted into setTimeout(callback, 1), so enter Timer During the stage, it will be judged based on the current time whether the timing exceeds 1ms.

  2. 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.

  3. 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 of 1ms is reached, the timeout 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:

  1. 进入 poll phase 轮询阶段之前会先检查是否有 timer 定时任务。

  2. 如果没有 timer 定时任务,才会执行后面的 IO 回调。

  3. 我们在 IO 回调中设置 setTimeout 定时任务,这时已经过了 timer 检查阶段,所以 timer 定时任务会被推迟到下一个循环中执行。

process.nextTick()

无论在事件循环的哪个阶段,只要使用 process.nextTick() 添加了回调任务,Node 都会在进入下一阶段之前把 nextTickQueue 队列中的任务执行完。

setTimeout(function() {
    setImmediate(() => {
        console.log('immediate');
    });
    process.nextTick(() => {
        console.log('nextTick');
    });
}, 0);
// nextTick
// immediate
Copy after login

上述代码中,总是先执行 nextTick 任务,就是因为在循环在进入下一个阶段之前会先执行 nextTickQueue 中的任务。下面代码的执行结果也符合预期。

setImmediate(() => {
    setTimeout(() => {
        console.log('timeout');
    }, 0);
    process.nextTick(() => {
        console.log('nextTick');
    });
});
// nextTick
// timeout
Copy after login

相关推荐:

关于Node异步 I/O的介绍

关于Node模块机制的解析

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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 implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

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 implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

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 forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

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).

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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 and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

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

See all articles