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!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
