search
HomeWeb Front-endJS TutorialDetailed interpretation of Node timer knowledge

Detailed interpretation of Node timer knowledge

Jun 04, 2018 pm 03:58 PM
nodetimerKnowledge

This article mainly introduces the relevant knowledge of Node timer. It is very good and has reference value. Friends in need can refer to it

JavaScript runs in a single thread, and asynchronous operations are particularly important.

As long as functions outside the engine are used, they need to interact with the outside, thus forming asynchronous operations. Because there are so many asynchronous operations, JavaScript has to provide a lot of asynchronous syntax. It's like, some people are always hit, and their ability to resist blows must become stronger, otherwise they will be finished.

Node’s asynchronous syntax is more complicated than that of a browser, because it can talk to the kernel, and a special library libuv has to be built to do this. This library is responsible for the execution time of various callback functions. After all, asynchronous tasks must eventually return to the main thread and be queued for execution one by one.

In order to coordinate asynchronous tasks, Node actually provides four timers so that tasks can run at specified times.

  • setTimeout()

  • setInterval()

  • setImmediate()

  • process.nextTick()

The first two are language standards, and the last two are unique to Node. They are written in similar ways and have similar functions, so it is not easy to distinguish them.

Can you tell me the result of running the following code?

// test.js
setTimeout(() => console.log(1));
setImmediate(() => console.log(2));
process.nextTick(() => console.log(3));
Promise.resolve().then(() => console.log(4));
(() => console.log(5))();

The running results are as follows.

$ node test.js

If you can get it right right away, you may not need to read any more. This article explains in detail how Node handles various timers, or more broadly, how the libuv library arranges asynchronous tasks to be executed on the main thread.

1. Synchronous tasks and asynchronous tasks

First of all, synchronous tasks are always executed earlier than asynchronous tasks.

In the previous piece of code, only the last line is a synchronization task, so it is executed earliest.

(() => console.log(5))();

2. This cycle and the second cycle

Asynchronous tasks can be divided into two types.

Add asynchronous tasks in this cycle
Add asynchronous tasks in the second cycle

The so-called "loop" refers to the event loop. This is how the JavaScript engine handles asynchronous tasks, which will be explained in detail later. Just understand here that this cycle must be executed earlier than the second cycle.

Node stipulates that the callback functions of process.nextTick and Promise are appended to this cycle, that is, once the synchronization tasks are completed, they will be executed. The callback functions of setTimeout, setInterval, and setImmediate are added in the second cycle.

This means that the third and fourth lines of the code at the beginning of the article must be executed earlier than the first and second lines.

// 下面两行,次轮循环执行
setTimeout(() => console.log(1));
setImmediate(() => console.log(2));
// 下面两行,本轮循环执行
process.nextTick(() => console.log(3));
Promise.resolve().then(() => console.log(4));

3. process.nextTick()

The name process.nextTick is a bit misleading. It is executed in this cycle, and It is the fastest execution among all asynchronous tasks.

#After Node has executed all synchronization tasks, it will then execute the task queue of process.nextTick. So, the following line of code is the second output.

process.nextTick(() => console.log(3));

Basically, if you want an asynchronous task to execute as fast as possible, use process.nextTick.

4. Microtasks

According to the language specifications, the callback function of the Promise object will enter the asynchronous task "Microtask" (microtask) queue.

The microtask queue is appended behind the process.nextTick queue and also belongs to this cycle. Therefore, the following code always outputs 3 first and then 4.

process.nextTick(() => console.log(3));
Promise.resolve().then(() => console.log(4));
// 3
// 4

Note that the next queue will not be executed until the previous queue is completely emptied.

process.nextTick(() => console.log(1));
Promise.resolve().then(() => console.log(2));
process.nextTick(() => console.log(3));
Promise.resolve().then(() => console.log(4));
// 1
// 3
// 2
// 4

In the above code, all callback functions of process.nextTick will be executed earlier than Promise.

At this point, the execution sequence of this cycle is finished.

同步任务
process.nextTick()
微任务

5. The concept of event loop

The following begins to introduce the execution sequence of the second cycle, which requires understanding what an event loop is ( event loop).

Node’s official documentation introduces it like this.

“When Node.js starts, it initializes the event loop, processes the provided input script which may make async API calls, schedule timers, or call process.nextTick(), then begins processing the event loop.”

This passage is very important and needs to be read carefully. It expresses three levels of meaning.

First of all, some people think that in addition to the main thread, there is a separate event loop thread. That's not the case, there is only one main thread, and the event loop is completed on the main thread.

其次,Node 开始执行脚本时,会先进行事件循环的初始化,但是这时事件循环还没有开始,会先完成下面的事情。

  • 同步任务

  • 发出异步请求

  • 规划定时器生效的时间

执行process.nextTick()等等

最后,上面这些事情都干完了,事件循环就正式开始了。

六、事件循环的六个阶段

事件循环会无限次地执行,一轮又一轮。只有异步任务的回调函数队列清空了,才会停止执行。

每一轮的事件循环,分成六个阶段。这些阶段会依次执行。

timers
I/O callbacks
idle, prepare
poll
check
close callbacks

每个阶段都有一个先进先出的回调函数队列。只有一个阶段的回调函数队列清空了,该执行的回调函数都执行了,事件循环才会进入下一个阶段。

下面简单介绍一下每个阶段的含义,详细介绍可以看官方文档,也可以参考 libuv 的源码解读。

(1)timers

这个是定时器阶段,处理setTimeout()和setInterval()的回调函数。进入这个阶段后,主线程会检查一下当前时间,是否满足定时器的条件。如果满足就执行回调函数,否则就离开这个阶段。

(2)I/O callbacks

除了以下操作的回调函数,其他的回调函数都在这个阶段执行。

  • setTimeout()和setInterval()的回调函数

  • setImmediate()的回调函数

  • 用于关闭请求的回调函数,比如socket.on('close', ...)

(3)idle, prepare

该阶段只供 libuv 内部调用,这里可以忽略。

(4)Poll

这个阶段是轮询时间,用于等待还未返回的 I/O 事件,比如服务器的回应、用户移动鼠标等等。

这个阶段的时间会比较长。如果没有其他异步任务要处理(比如到期的定时器),会一直停留在这个阶段,等待 I/O 请求返回结果。

(5)check

该阶段执行setImmediate()的回调函数。

(6)close callbacks

该阶段执行关闭请求的回调函数,比如socket.on('close', ...)

七、事件循环的示例

下面是来自官方文档的一个示例。

const fs = require('fs');
const timeoutScheduled = Date.now();
// 异步任务一:100ms 后执行的定时器
setTimeout(() => {
 const delay = Date.now() - timeoutScheduled;
 console.log(`${delay}ms`);
}, 100);
// 异步任务二:至少需要 200ms 的文件读取
fs.readFile('test.js', () => {
 const startCallback = Date.now();
 while (Date.now() - startCallback < 200) {
 // 什么也不做
 }
});

上面代码有两个异步任务,一个是 100ms 后执行的定时器,一个是至少需要 200ms 的文件读取。请问运行结果是什么?

脚本进入第一轮事件循环以后,没有到期的定时器,也没有已经可以执行的 I/O 回调函数,所以会进入 Poll 阶段,等待内核返回文件读取的结果。由于读取小文件一般不会超过 100ms,所以在定时器到期之前,Poll 阶段就会得到结果,因此就会继续往下执行。

第二轮事件循环,依然没有到期的定时器,但是已经有了可以执行的 I/O 回调函数,所以会进入 I/O callbacks 阶段,执行fs.readFile的回调函数。这个回调函数需要 200ms,也就是说,在它执行到一半的时候,100ms 的定时器就会到期。但是,必须等到这个回调函数执行完,才会离开这个阶段。

第三轮事件循环,已经有了到期的定时器,所以会在 timers 阶段执行定时器。最后输出结果大概是200多毫秒。

八、setTimeout 和 setImmediate

由于setTimeout在 timers 阶段执行,而setImmediate在 check 阶段执行。所以,setTimeout会早于setImmediate完成。

setTimeout(() => console.log(1));
setImmediate(() => console.log(2));

上面代码应该先输出1,再输出2,但是实际执行的时候,结果却是不确定,有时还会先输出2,再输出1。

这是因为setTimeout的第二个参数默认为0。但是实际上,Node 做不到0毫秒,最少也需要1毫秒,根据官方文档,第二个参数的取值范围在1毫秒到2147483647毫秒之间。也就是说,setTimeout(f, 0)等同于setTimeout(f, 1)

实际执行的时候,进入事件循环以后,有可能到了1毫秒,也可能还没到1毫秒,取决于系统当时的状况。如果没到1毫秒,那么 timers 阶段就会跳过,进入 check 阶段,先执行setImmediate的回调函数。

但是,下面的代码一定是先输出2,再输出1。

const fs = require(&#39;fs&#39;);
fs.readFile(&#39;test.js&#39;, () => {
 setTimeout(() => console.log(1));
 setImmediate(() => console.log(2));
});

上面代码会先进入 I/O callbacks 阶段,然后是 check 阶段,最后才是 timers 阶段。因此,setImmediate才会早于setTimeout执行。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

JS实现的集合去重,交集,并集,差集功能示例

Bootstrap 中data-[*] 属性的整理

基于Axios 常用的请求方法别名(详解)

The above is the detailed content of Detailed interpretation of Node timer knowledge. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools