Home>Article>Web Front-end> Quickly understand the event loop in Node.js in one article
This article will take you to understand the event loop inNode.jsasynchronous programming. The event loop is a very important part of implementing Node's non-blocking I/O! Event loop and non-blocking I/O are all underlying capabilities of the C library LIBUV. Once you understand the event loop and non-blocking I/O, you will understand how Node's asynchronous operation works!
#Node’s own execution model, the event loop, is what makes callback functions so common. [Recommended learning: "nodejs Tutorial"]
When the process starts, Node will create a loop similar towhile(true)
, and each time the loop is executed The physical process is calledTick
. The process of eachTick
is to check whether there is an event to be processed, and if so, retrieve the event and its related callback function. If associated callback functions exist, they are executed. Then enter the next loop. If there are no more events to handle, exit the process
Tick flow chart
The event loop is a very important part of realizing Node.js non-blocking I/O! Event loop and non-blocking I/O are the underlying capabilities of theLIBUV
C library. Once you understand the event loop and non-blocking I/O, you will understand how the asynchronous operation of Node.js works!
const eventloop = { queue: [], // 循环方法 loop() { // 不停的检测队列是否还有未循环的消息 while (this.queue.length) { const callback = this.queue.shift(); callback(); } // 执行下一次循环 // 小知识点 JS的 this绑定 setTimeout(this.loop.bind(this), 50); }, // 添加消息到队列 add(callback) { this.queue.push(callback); }, }; eventloop.loop(); setTimeout(() => { eventloop.add(() => { console.log("第一个"); }); }, 500); setTimeout(() => { eventloop.add(() => { console.log("第二个"); }); }, 800);
The above is the most basic example of the event loop. We can add messages to it, and then it will check whether There are events that have not been processed. If there are, event processing will be performed.
For more programming-related knowledge, please visit:programming video! !
The above is the detailed content of Quickly understand the event loop in Node.js in one article. For more information, please follow other related articles on the PHP Chinese website!