This article will take you to understand the eventloop in Node.js
The main thread reads events from the "task queue". This process is cyclic, so the entire running mechanism is also called Event Loop. The following article will help you master the eventloop in Node.js. I hope it will be helpful to you!
#In fact, I also talked about the eventloop in the browser in the previous article. However, the eventloop in NodeJs is different from that in the browser. Mastering eventloop is a very important skill for people who write nodejs. Because this means that you can not only write js, but also study NodeJs.
Why is there an eventloop?
We know that the essence of NodeJs is to move the browser's v8 to run in the operating system, so it also takes over the browser's event loop. But why does a design like eventloop appear?
From a historical perspective, js was designed as a very simple language for operating dom on the page (I believe everyone has heard the story that js was designed in only 10 days). For this goal, we certainly hope that the execution of js will be as simple and lightweight as possible. How lightweight can it be? The rendering engine as light as js runs in a thread.
Then the problem comes. If js is run on a thread, when the code is linear, of course there is no problem. But on the page, we need user interactions, and these interactions don't know why and when they happen. How to deal with js? If there is running code in front of you, how should the program react when a user interacts? If the user interaction is processed first, the original program will be suspended (that is, blocked). In order to avoid this kind of blocking, js adopts a method, which is to use a message queue to store this kind of user interaction. After all the programs have finished running, go to the message queue to get the interaction event, and then execute it. This solves the blocking problem.
Browser eventloop
We all know that when the browser is browsing the page, user interaction may occur at any time, in order to respond to the user immediately. js will not be closed, it will keep looping. It is roughly as follows:
向消息队列拿任务-->执行任务-->执行完毕--> 向消息队列拿任务--> ....
Of course, we have mentioned in the previous event loop article that in order to classify different asynchronous tasks, there is actually a distinction between macro tasks and micro tasks in the event loop. Their execution is roughly
向消息队列拿微任务-->执行微任务-->微任务执行完毕--> 向消息队列拿宏任务-->执行宏任务-->宏任务执行完毕-->向消息队列拿微任务-->...
NodeJs's eventloop
node's event loop is actually similar to that on the browser. However, nodeJs distinguishes different macro tasks at different times. The following is the official flow chart:
You can see that each event loop in nodeJs is divided into 6 specific periods, and each period will use designated macro tasks. Then before the macro tasks of each period are executed, the micro task queue will be executed first.
Overview
timers | Executed by setTimeout() and setInterval() Triggered callbacks | |
---|---|---|
##pending callbacks | Execution is delayed until I/O callbacks for the next loop iteration||
idle, prepare | are only used internally, developers may not pay attention||
poll | Retrieve new I/O events; execute I/O related callbacks (almost all callbacks will be executed except close callbacks and timers scheduling The callbacks and callbacks scheduled by setImmediate() will block at this stage at the appropriate time)||
check | ExecutionsetImmediate() | |
close callbacks | For examplesocket.on('close', ...) |
任务 | 浏览器 | Node |
---|---|---|
I/O | ✅ | ✅ |
setTimeout | ✅ | ✅ |
setInterval | ✅ | ✅ |
setImmediate | ❌ | ✅ |
requestAnimationFrame | ✅ | ❌ |
微任务:
任务 | 浏览器 | Node |
---|---|---|
process.nextTick | ❌ | ✅ |
MutationObserver | ✅ | ❌ |
Promise.then catch finally | ✅ | ✅ |
可以看到process.nextTick是nodejs特有的微任务,不仅如此,process.nextTick()的优先级高于所有的微任务,每一次清空微任务列表的时候,都是先执行 process.nextTick()
执行差异
不仅是任务类型上有差异,在执行上2个环境其实也有差异。在浏览器上执行任务的时候,每执行一个宏任务之前,需要先确保微任务队列执行完了。而在nodejs上是每个时期之前,先确保微任务队列执行完。也就是说在假如在timer时期,会先把所有setTimeout,setInterval的宏任务执行完。在执行完微任务,再进入下个时期。
注意:以上执行规则是在nodejs的v11版本之前的规则。在11版本之后nodejs的执行输出是跟浏览器一样的。
setImmediate() vs setTimeout()
setImmediate() 和 setTimeout()的执行先后顺序是不一定的,就是说如果你不停地执行以下代码,每次得到的结果可能是不一样的。
setTimeout(() => { console.log('timeout'); }, 0); setImmediate(() => { console.log('immediate'); });
其中的原因是程序对时间的处理是有误差的。在setTimeout方法中设置的时间,不一定是准确的。同时在回调触发时,也无法确认事件循环处在哪个时期,可能是timer,也可能是check。所有会有不同的结果。
总结
eventloop是js运行机制里的重点内容,对于NodeJs来说,eventloop的操作空间则更大。因为它被细分为不同的时期,从而让我们可能把逻辑进一步细化。同时利用nextTick的最高优先级,可以写出在浏览器无法实现的代码。因此对于深入NodeJs的开发者来说,eventloop往往是他们考察新人对NodeJs理解的第一步。
更多node相关知识,请访问:nodejs 教程!!
The above is the detailed content of This article will take you to understand the eventloop in Node.js. 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



The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

Choosing a Docker image for Node may seem like a trivial matter, but the size and potential vulnerabilities of the image can have a significant impact on your CI/CD process and security. So how do we choose the best Node.js Docker image?

Node 19 has been officially released. This article will give you a detailed explanation of the 6 major features of Node.js 19. I hope it will be helpful to you!

How does Node.js do GC (garbage collection)? The following article will take you through it.

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

The reason why node cannot use the npm command is because the environment variables are not configured correctly. The solution is: 1. Open "System Properties"; 2. Find "Environment Variables" -> "System Variables", and then edit the environment variables; 3. Find the location of nodejs folder; 4. Click "OK".
