Table of Contents
libuv
Question
event-loop in nodeJs
timers
poll
check
小总结
案例
了解下浏览器和node的event-loop差异在什么地方
关于 process.nextTick()和setImmediate
process.nextTick()
event-loop核心思维导图
结束语
Home Web Front-end JS Tutorial An article to talk about the event-loop mechanism in Node.js

An article to talk about the event-loop mechanism in Node.js

Nov 05, 2021 am 09:48 AM
node.js

This article will take you to understand the event-loop (time loop) mechanism in Node.js. I hope it will be helpful to you!

An article to talk about the event-loop mechanism in Node.js

Today we will learn about event-loop in nodeJs. The understanding of event-loop has always been a big difficulty for me. I hope to break through this difficulty through this study. I also hope to deepen my understanding and impression of event-loop through this blog.

libuv

Before learning event-loop, first understand the libuv of node. libuv is responsible for the implementation of different I/O models on different operating systems, and abstracts different implementations into APIs that can be used with third-party applications.

An article to talk about the event-loop mechanism in Node.js

Question

Before formally learning event-loop, let’s think about a question

    setTimeout(() => {
      console.log("timer1");
      Promise.resolve().then(() => {
        console.log("promise1");
      });
    }, 0);

    setTimeout(() => {
      console.log("timer2");
      Promise.resolve().then(() => {
        console.log("promise2");
      });
    }, 0);
Copy after login

This code What is the result of running it in the browser?

An article to talk about the event-loop mechanism in Node.js

What is the result of running it in node?

Before node8.6:

An article to talk about the event-loop mechanism in Node.js

##After node8.6:

An article to talk about the event-loop mechanism in Node.js

Why there is such a result, we will analyze it later!

event-loop in nodeJs

First of all, Let’s look at a picture:

An article to talk about the event-loop mechanism in Node.js

#You can see 6 stages in the picture, namely: timers, pending callbacks, idle/prepare, poll, check, close callbacks.

  • timers phase: mainly execute setTimeOut, setInterval callbacks

  • pending callbacks phase: execute some system call errors, such as network communication Error callback

  • idle/prepare phase: only used within the system (we cannot control and interfere with this phase)

  • poll phase: get new I/O events, such as getting an I/O callback for reading a file.

    Under appropriate circumstances, nodejs will block in this phase

  • check phase: execute setImmediate callback

  • For example Execute the destroy and close event callbacks of sokect

Each stage follows a

FIFO(First in first out) rule to execute the task queue tasks inside. Among these six stages, we focus on the timers, poll, check stages. Most of the asynchronous tasks in our daily development are handled in these three stages.

timers

Let’s talk about the timers stage first.


Timers is the first stage of the event loop. Nodejs will check whether there is an expired timer, and if so, put its callback into the queue. However, nodejs cannot guarantee that the timer will execute the callback immediately when the preset event arrives. This is because the expiration check of the timer by nodejs is not necessarily reliable. It will be affected by other running programs on the machine, or it will encounter the current main thread. Not idle situation. Regarding the uncertainty here, the official website gives an example:
First declare a setTimeOut, and then read a file externally. When the file reading operation exceeds the timer time, in this way, the read File operations will delay the timer's callback. This is the situation where the main thread is not idle as mentioned earlier.

poll

The poll phase mainly performs two things:

1. Process the task queue of the poll phase

2. When there is a timer that has timed out, its callback function is executed

An article to talk about the event-loop mechanism in Node.js

In the above figure, we can also see:

After executing the poll task queue in the poll phase After the task, it will check whether there is a preset setImmediate. If there is, it will enter the check phase. If not, nodejs will block here.

Here we will have a question. If it is blocked in the poll stage, wouldn't the timer we set cannot be executed?

In fact
When the event-loop is blocked in the poll phase, nodejs will have a checking mechanism. It will check whether the timers queue is empty. If it is not empty, it will re-enter the timers phase.

check

The check phase mainly executes the setImmediate callback function.

小总结

event-loop的每个阶段都有一个队列,当event-loop达到某个阶段之后,将执行这个阶段的任务队列,直到队列清空或者达到系统规定的最大回调限制之后,才会进入下一个阶段。当所有阶段都执行完成一次之后,称event-loop完成一个tick。

案例

上面我们说完了event-loop的理论部分,但是光有理论我们也还是不能很清晰的理解event-loop。下面我们就根据几个demo来更加深入的理解下event-loop!

demo1

    const fs=require('fs')
    fs.readFile('test.txt',()=>{
            console.log('readFile')
            setTimeout(()=>{
                    console.log('settimeout');
            },0)
            setImmediate(()=>{
                    console.log('setImmediate')
            })
    })
Copy after login

执行结果:

An article to talk about the event-loop mechanism in Node.js

可见执行结果跟我们前面的分析时一致的!

demo2

    const fs = require("fs");
    const EventEmitter = require("events").EventEmitter;
    let pos = 0;
    const messenger = new EventEmitter();

    messenger.on("message", function (msg) {
      console.log(++pos + " message:" + msg); //
    });

    console.log(++pos + " first"); //

    process.nextTick(function () {
      console.log(++pos + " nextTick"); //
    });

    messenger.emit("message", "hello!");
    fs.stat(__filename, function () {
      console.log(++pos + " stat"); //
    });

    setTimeout(function () {
      console.log(++pos + " quick timer"); //
    }, 0);
    setTimeout(function () {
      console.log(++pos + " long timer"); //
    }, 30);
    setImmediate(function () {
      console.log(++pos + " immediate"); //
    });

    console.log(++pos + " last"); //
Copy after login

结果:

An article to talk about the event-loop mechanism in Node.js

了解下浏览器和node的event-loop差异在什么地方

在node 8.6 之前:

浏览器中的微任务队列会在每个宏任务执行完成之后执行,而node中的微任务会在事件循环的各个阶段之间执行,即每个阶段执行完成之后会去执行微任务队列。

在8.6之后:

浏览器和node中微任务的执行是一致的!

所以,在文章开头,我们提出的思考的问题就有了结果。

关于 process.nextTick()和setImmediate

process.nextTick()

语法:process.nextTick(callback,agrs)

执行时机:

这个函数其实是独立于 Event Loop 之外的,它有一个自己的队列,当每个阶段完成后,如果存在 nextTick 队列,就会清空队列中的所有回调函数,并且优先于其他 microtask 执行。递归的调用process.nextTick()会导致I/O starving,官方推荐使用setImmediate()

关于starving现象的说明:

    const fs = require("fs");
    fs.readFile("test.txt", (err, msg) => {
      console.log("readFile");
    });

    let index = 0;

    function handler() {
      if (index >= 30) return;
      index++;
      console.log("nextTick" + index);
      process.nextTick(handler);
    }

    handler();
Copy after login

运行结果:

An article to talk about the event-loop mechanism in Node.js

可以看到,等到nextTick函数呗执行30次之后,读取文件的回调才被执行!这样的现象被称为 I/O 饥饿

当我们把 process.nextTick 换为 setImmediate

    const fs = require("fs");
    fs.readFile("test.txt", (err, msg) => {
      console.log("readFile");
    });

    let index = 0;

    function handler() {
      if (index >= 30) return;
      index++;
      console.log("nextTick" + index);
      setImmediate(handler);
    }

    handler();
Copy after login

结果:

An article to talk about the event-loop mechanism in Node.js

造成这两种差异的原因是,嵌套调用的setImmediate的回调被排到了下一次event-loop中去!

event-loop核心思维导图

1An article to talk about the event-loop mechanism in Node.js

结束语

通过今天的学习,让我对event-loop的理解更深刻了。那么,下次见。好好学习,天天向上!

1An article to talk about the event-loop mechanism in Node.js

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of An article to talk about the event-loop mechanism in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

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

Detailed graphic explanation of the memory and GC of the Node V8 engine Detailed graphic explanation of the memory and GC of the Node V8 engine Mar 29, 2023 pm 06:02 PM

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!

Let's talk in depth about the File module in Node Let's talk in depth about the File module in Node Apr 24, 2023 pm 05:49 PM

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.

Let's talk about how to choose the best Node.js Docker image? Let's talk about how to choose the best Node.js Docker image? Dec 13, 2022 pm 08:00 PM

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.js 19 is officially released, let's talk about its 6 major features! Node.js 19 is officially released, let's talk about its 6 major features! Nov 16, 2022 pm 08:34 PM

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!

Let's talk about the GC (garbage collection) mechanism in Node.js Let's talk about the GC (garbage collection) mechanism in Node.js Nov 29, 2022 pm 08:44 PM

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

Let's talk about the event loop in Node Let's talk about the event loop in Node Apr 11, 2023 pm 07:08 PM

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!

What should I do if node cannot use npm command? What should I do if node cannot use npm command? Feb 08, 2023 am 10:09 AM

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".

See all articles