Home >Web Front-end >JS Tutorial >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.
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.
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
向消息队列拿微任务-->执行微任务-->微任务执行完毕--> 向消息队列拿宏任务-->执行宏任务-->宏任务执行完毕-->向消息队列拿微任务-->...
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.
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() 和 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!