Home > Web Front-end > JS Tutorial > Analysis of the event loop in Node

Analysis of the event loop in Node

不言
Release: 2018-07-20 10:30:00
Original
1325 people have browsed it

This article introduces to you the analysis of the event loop in Node. It has certain reference value. Friends in need can refer to it.

Each stage in the event loop

The event loop process of Node.js is roughly as follows:

   ┌───────────────────────────┐
┌─>│           timers          │
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │     pending callbacks     │
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │       idle, prepare       │
│  └─────────────┬─────────────┘      ┌───────────────┐
│  ┌─────────────┴─────────────┐      │   incoming:   │
│  │           poll            │<─────┤  connections, │
│  └─────────────┬─────────────┘      │   data, etc.  │
│  ┌─────────────┴─────────────┐      └───────────────┘
│  │           check           │
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
└──┤      close callbacks      │
   └───────────────────────────┘
Copy after login

Each stage has its own task queue. When the task of this stage After all queues have been executed, or the maximum number of tasks executed has been reached, it will enter the next stage.

timers phase

This phase will execute the scheduled tasks set by setTimeout and setInterval.
Of course, this timing is not accurate, but after the timing time is exceeded, once the execution opportunity is obtained, it will be executed immediately.

pending callbacks stage

This stage will perform some operations related to the underlying system, such as errors returned by TCP connections, etc. When these errors occur, they will be postponed by Node to the next cycle.

Polling phase

This phase is used to execute callbacks related to IO operations. Node will ask the operating system whether a new IO event has been triggered, and then execute the corresponding event. callback. Almost all operations except timer events, setImmediate() and close callbacks will be performed during this phase.

check phase

This phase will execute the tasks set by setImmediate().

close callbacks phase

If a socket or handle(handle) is suddenly closed, for example through socket.destroy() is closed, the close event will be emitted at this stage.

Specific execution of the event loop

After the event loop is initialized, it will proceed according to the process shown in the figure above:

  1. First, the timer will be executed in sequence Tasks in pending callback callback;

  2. and then enters the idle and prepare stages, where Node will be executed Some internal logic;

  3. and then enters the poll polling phase. At this stage, all IO callbacks will be executed, such as reading files, network operations, etc. The poll stage has a poll queue task queue. The execution process of this stage is relatively long, as follows:

  • Entering this stage, it will first check whether the timeout timing queue is available. The executed task, if any, will jump to the timer stage for execution.

  • If there is no timer task, the poll queue task queue will be checked. If it is not empty, all tasks will be traversed and executed until they are all The execution is completed or the maximum number of tasks that can be executed is reached.

  • poll queue After the task queue is executed, it will check whether there are tasks in the setImmediate task queue. If so, the event loop will transfer Go to the next check stage.

  • If there is no setImmediate task, then Node will wait here for the arrival of new IO callbacks and execute them immediately.

Note: This waiting will not continue forever. Instead, after reaching a certain limit, it will continue to the next stage for execution.

setTimeout() and setImmediate()

A little secret

It’s not actually a secret, but I’m I just found out after checking the information.
That is: in Node, setTimeout(callback, 0) will be converted to setTimeout(callback, 1).
Please refer here for details.

setTimeout() and setImmediate() Execution order

The execution order of the following two scheduled tasks performs inconsistently under different circumstances. .

setTimeout(function() {
    console.log(&#39;timeout&#39;);
}, 0);

setImmediate(function() {
    console.log(&#39;immediate&#39;);
});
Copy after login

Set the timer in ordinary code

If you set these two scheduled tasks in the ordinary code execution stage (for example, in the outermost code block), their execution order is different. stable.

  1. First of all, the setTimeout(callback, 0) we set has been converted into setTimeout(callback, 1), so enter Timer During the stage, it will be judged based on the current time whether the timing exceeds 1ms.

  2. Before the event loop enters the timer phase, the system calls a method to update the current time. Since other programs are running in the system at the same time, the system needs to wait for the processes of other programs to end. Get the accurate time, so there may be a certain delay in updating the time.

  3. When updating the time, if there is no delay, the timing is less than 1ms,immediate The task will be executed first; if there is a delay, and this time When the limit of 1ms is reached, the timeout task will be executed first.

Set the timer in the IO callback

If we set these two timers in the IO callback, then the setImmediate task will first Executed for the following reasons:

  1. 进入 poll phase 轮询阶段之前会先检查是否有 timer 定时任务。

  2. 如果没有 timer 定时任务,才会执行后面的 IO 回调。

  3. 我们在 IO 回调中设置 setTimeout 定时任务,这时已经过了 timer 检查阶段,所以 timer 定时任务会被推迟到下一个循环中执行。

process.nextTick()

无论在事件循环的哪个阶段,只要使用 process.nextTick() 添加了回调任务,Node 都会在进入下一阶段之前把 nextTickQueue 队列中的任务执行完。

setTimeout(function() {
    setImmediate(() => {
        console.log('immediate');
    });
    process.nextTick(() => {
        console.log('nextTick');
    });
}, 0);
// nextTick
// immediate
Copy after login

上述代码中,总是先执行 nextTick 任务,就是因为在循环在进入下一个阶段之前会先执行 nextTickQueue 中的任务。下面代码的执行结果也符合预期。

setImmediate(() => {
    setTimeout(() => {
        console.log('timeout');
    }, 0);
    process.nextTick(() => {
        console.log('nextTick');
    });
});
// nextTick
// timeout
Copy after login

相关推荐:

关于Node异步 I/O的介绍

关于Node模块机制的解析

The above is the detailed content of Analysis of the event loop in Node. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template