Home>Article>Web Front-end> Quickly understand the event loop in Node.js in one article

Quickly understand the event loop in Node.js in one article

青灯夜游
青灯夜游 forward
2021-07-05 10:58:14 1581browse

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!

Quickly understand the event loop in Node.js in one article

#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 eachTickis 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

Quickly understand the event loop in Node.js in one article
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 theLIBUVC library. Once you understand the event loop and non-blocking I/O, you will understand how the asynchronous operation of Node.js works!

Simulate eventloop through code

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.

Each event loop is a new call stack

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!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete