search
HomeWeb Front-endJS TutorialThis article will take you to understand the timer queue in the Node event loop

This article will take you to understand the timer queue in the Node event loop

In Previous article, we discussed the microtask queue and its priority order in each queue. In this article, we will discuss timer queues, another queue in Node.js for handling asynchronous code.

Before we delve into timer queues, let’s take a quick look at microtask queues. To enqueue the callback function into the microtask queue, we use functions such as process.nextTick() and Promise.resolve(). Microtask queues have the highest priority when it comes to executing asynchronous code in Node.js. [Related tutorial recommendations: nodejs video tutorial, Programming teaching]

Enqueue callback function

Now we go to Timer queue. To queue a callback function into a timer queue, we can use functions such as setTimeout and setInterval. For convenience of explanation, this article will use setTimeout.

In order to understand the execution order of the timer queue, we will conduct a series of experiments to enqueue tasks in the microtask queue and timer queue.

Experiment Three

Code

// index.js
setTimeout(() => console.log("this is setTimeout 1"), 0);
setTimeout(() => console.log("this is setTimeout 2"), 0);
setTimeout(() => console.log("this is setTimeout 3"), 0);

process.nextTick(() => console.log("this is process.nextTick 1"));
process.nextTick(() => {
  console.log("this is process.nextTick 2");
  process.nextTick(() =>
    console.log("this is the inner next tick inside next tick")
  );
});
process.nextTick(() => console.log("this is process.nextTick 3"));

Promise.resolve().then(() => console.log("this is Promise.resolve 1"));
Promise.resolve().then(() => {
  console.log("this is Promise.resolve 2");
  process.nextTick(() =>
    console.log("this is the inner next tick inside Promise then block")
  );
});
Promise.resolve().then(() => console.log("this is Promise.resolve 3"));

Translation Note: Don’t be nervous, this code is in the previous article Based on the "welfare experiment", three setTimeout statements were added at the beginning.

This code contains three process.nextTick() calls, three Promise.resolve() calls and three setTimeout call. Each callback function logs the appropriate message. All three setTimeout calls have a delay of 0ms, which means that when each setTimeout statement is executed, the callback function is immediately enqueued to the timer queue to wait. . The second process.nextTick() and the second Promise.resolve() have an additional process.nextTick() statement, and each All have a callback function.

Visualization

This article will take you to understand the timer queue in the Node event loop

#When the call stack executes all statements, there are 3 callbacks in the nextTick queue and 3 callbacks in the Promise queue. 3 callbacks, there are also 3 callbacks in the timer queue. There is no code to execute and control passes to the event loop.

nextTick queue has the highest priority, followed by Promise queue, then timer queue. Get the 1st callback from the nextTick queue and execute it, logging a message to the console. Then get the 2nd callback and execute it, which will also log a message. The second callback contains a call to process.nextTick(), which adds a new callback to the nextTick queue. Continue execution and get and execute the 3rd callback and log a message. Finally, we take out the callback function newly added to the nextTick queue and execute it in the call stack, thus outputting the fourth log message on the console.

When the nextTick queue is empty, the event loop turns to the Promise queue. Get the first callback from the queue and print a message to the console. The second callback has a similar effect and also adds a callback to the nextTick queue. The third callback in the Promise is executed, and the log message is output. At this time, the Promise queue is empty, and the event loop checks the nextTick queue to see if there is a new callback. Once found, the message is also logged to the console.

Now, both microtask queues are empty, and the event loop turns to the timer queue. We have three callbacks, each of which is taken from the timer queue and executed on the call stack, will print "setTimeout 1", "setTimeout 2" and "setTimeout 3" respectively.

this is process.nextTick 1
this is process.nextTick 2
this is process.nextTick 3
this is the inner next tick inside next tick
this is Promise.resolve 1
this is Promise.resolve 2
this is Promise.resolve 3
this is the inner next tick inside Promise then block
this is setTimeout 1
this is setTimeout 2
this is setTimeout 3

Inference

The callback function in the microtask queue will be executed before the callback function in the timer queue.

So far, the priority order is the nextTick queue, followed by the Promise queue, and then the timer queue. Now let's move on to the next experiment.

Experiment 4

// index.js
setTimeout(() => console.log("this is setTimeout 1"), 0);
setTimeout(() => {
  console.log("this is setTimeout 2");
  process.nextTick(() =>
    console.log("this is inner nextTick inside setTimeout")
  );
}, 0);
setTimeout(() => console.log("this is setTimeout 3"), 0);

process.nextTick(() => console.log("this is process.nextTick 1"));
process.nextTick(() => {
  console.log("this is process.nextTick 2");
  process.nextTick(() =>
    console.log("this is the inner next tick inside next tick")
  );
});
process.nextTick(() => console.log("this is process.nextTick 3"));

Promise.resolve().then(() => console.log("this is Promise.resolve 1"));
Promise.resolve().then(() => {
  console.log("this is Promise.resolve 2");
  process.nextTick(() =>
    console.log("this is the inner next tick inside Promise then block")
  );
});
Promise.resolve().then(() => console.log("this is Promise.resolve 3"));

The code for the fourth experiment is mostly the same as the third one, with one exception. The callback function passed to the second setTimeout function now contains a call to process.nextTick().

Visualization

assets_YJIGb4i01jvw0SRdL5Bt_c4034ba006d840128b729005183abdf4_compressed (1).gif

让我们应用从之前的实验中学到的知识,快进到回调在微任务队列中已经被执行的点。假设我们有三个回调在计时器队列中排队等待。第一个回调出队并在调用堆栈上执行,“setTimeout 1”消息打印到控制台。事件循环继续运行第二个回调,“setTimeout 2”消息打印到控制台。同时,也会有一个回调函数入队了 nextTick 队列。

在执行计时器队列中的每个回调后,事件循环会返回检查微任务队列。检查 nextTick 队列确定需要执行的回调函数。这时第二个 setTimeout 推入的回调函数出队并在调用栈上执行,结果“inner nextTick”消息打印到控制台。

现在微任务队列为空了,控制权返回到计时器队列,最后一个回调被执行,控制台上显示消息“setTimeout 3”。

this is process.nextTick 1
this is process.nextTick 2
this is process.nextTick 3
this is the inner next tick inside next tick
this is Promise.resolve 1
this is Promise.resolve 2
this is Promise.resolve 3
this is the inner next tick inside Promise then block
this is setTimeout 1
this is setTimeout 2
this is inner nextTick inside setTimeout
this is setTimeout 3

推论

微任务队列中的回调函数会在定时器队列中的回调函数执行之间被执行。

实验五

代码

// index.js
setTimeout(() => console.log("this is setTimeout 1"), 1000);
setTimeout(() => console.log("this is setTimeout 2"), 500);
setTimeout(() => console.log("this is setTimeout 3"), 0);

该代码包含三个 setTimeout 语句,包含三个不同的、入队时机不一样的回调函数。第一个 setTimeout 延迟 1000 毫秒,第二个延迟 500 毫秒,第三个延迟 0 毫秒。当执行这些回调函数时,它们只是简单地将一条消息记录到控制台中。

可视化

由于代码片段的执行非常简单,因此我们将跳过可视化实验。当多个 setTimeout 调用被发出时,事件循环首先排队最短延迟的一个并在其他之前执行。结果,我们观察到“setTimeout 3”先执行,然后是“setTimeout 2”,最后是“setTimeout 1”。

this is setTimeout 3
this is setTimeout 2
this is setTimeout 1

推论

计时器队列回调按照先进先出(FIFO)的顺序执行。

总结

实验表明,微任务队列中的回调比定时器队列中的回调具有更高优先级,并且微任务队列中的回调在定时器队列中的回调之间执行。定时器队列遵循先进先出(FIFO)顺序。

原文链接:Visualizing The Timer Queue in Node.js Event Loop,2023年4月4日,by Vishwas Gopinath

更多node相关知识,请访问:nodejs 教程

The above is the detailed content of This article will take you to understand the timer queue in the Node event loop. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
5个常见的JavaScript内存错误5个常见的JavaScript内存错误Aug 25, 2022 am 10:27 AM

JavaScript 不提供任何内存管理操作。相反,内存由 JavaScript VM 通过内存回收过程管理,该过程称为垃圾收集。

实战:vscode中开发一个支持vue文件跳转到定义的插件实战:vscode中开发一个支持vue文件跳转到定义的插件Nov 16, 2022 pm 08:43 PM

vscode自身是支持vue文件组件跳转到定义的,但是支持的力度是非常弱的。我们在vue-cli的配置的下,可以写很多灵活的用法,这样可以提升我们的生产效率。但是正是这些灵活的写法,导致了vscode自身提供的功能无法支持跳转到文件定义。为了兼容这些灵活的写法,提高工作效率,所以写了一个vscode支持vue文件跳转到定义的插件。

巧用CSS实现各种奇形怪状按钮(附代码)巧用CSS实现各种奇形怪状按钮(附代码)Jul 19, 2022 am 11:28 AM

本篇文章带大家看看怎么使用 CSS 轻松实现高频出现的各类奇形怪状按钮,希望对大家有所帮助!

Node.js 19正式发布,聊聊它的 6 大特性!Node.js 19正式发布,聊聊它的 6 大特性!Nov 16, 2022 pm 08:34 PM

Node 19已正式发布,下面本篇文章就来带大家详解了解一下Node.js 19的 6 大特性,希望对大家有所帮助!

浅析Vue3动态组件怎么进行异常处理浅析Vue3动态组件怎么进行异常处理Dec 02, 2022 pm 09:11 PM

Vue3动态组件怎么进行异常处理?下面本篇文章带大家聊聊Vue3 动态组件异常处理的方法,希望对大家有所帮助!

聊聊如何选择一个最好的Node.js Docker镜像?聊聊如何选择一个最好的Node.js Docker镜像?Dec 13, 2022 pm 08:00 PM

选择一个Node​的Docker镜像看起来像是一件小事,但是镜像的大小和潜在漏洞可能会对你的CI/CD流程和安全造成重大的影响。那我们如何选择一个最好Node.js Docker镜像呢?

聊聊Node.js中的 GC (垃圾回收)机制聊聊Node.js中的 GC (垃圾回收)机制Nov 29, 2022 pm 08:44 PM

Node.js 是如何做 GC (垃圾回收)的?下面本篇文章就来带大家了解一下。

【6大类】实用的前端处理文件的工具库,快来收藏吧!【6大类】实用的前端处理文件的工具库,快来收藏吧!Jul 15, 2022 pm 02:58 PM

本篇文章给大家整理和分享几个前端文件处理相关的实用工具库,共分成6大类一一介绍给大家,希望对大家有所帮助。

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools