Home Web Front-end JS Tutorial A brief discussion on timers in Node.js_node.js

A brief discussion on timers in Node.js_node.js

May 16, 2016 pm 03:54 PM
node.js timer

Implementation of timer in Node.js

As mentioned in the previous blog post, the timer in Node is not implemented by opening a new thread, but directly in the event loop. The following uses several JavaScript timer examples and Node related source code to analyze how the timer function is implemented in Node.

Features of the timer function in JavaScript

Whether it is Node or the browser, there are two timer functions, setTimeout and setInterval, and their working characteristics are basically the same, so the following only uses Node as an example for analysis.

We know that the timer in JavaScript is not different from the underlying scheduled interrupt of the computer. When an interrupt arrives, the currently executing code will be interrupted and transferred to the scheduled interrupt processing function. When the JavaScript timer expires, if there is no code being executed in the current execution thread, the corresponding callback function will be executed; if there is code currently being executed, the JavaScript engine will neither interrupt the current code to execute the callback, nor start The new thread executes the callback, but it is processed after the current code is executed.

console.time('A')
setTimeout(function () {
  console.timeEnd('A');
}, 100);
var i = 0;
for (; i < 100000; i++) { }
Copy after login

Executing the above code, you can see that the final output time is not about 100ms, but a few seconds. This shows that the scheduled callback function is indeed not executed before the loop is completed, but is postponed until the end of the loop. In fact, during the execution of JavaScript code, all events cannot be processed, and new events must be processed until the current code is completed. This is why the browser becomes unresponsive when running time-consuming JavaScript code in it. In order to deal with this situation, we can use the Yielding Processes technique to divide the time-consuming code into small chunks (chunks), execute setTimeout once after each chunk is processed, and agree to process the next chunk after a short period of time. During this period During idle time, the browser/Node can process queued events.

Supplementary information

Advanced timers and Yielding Processes are discussed in more detail in Chapter 22 Advanced Techniques of JavaScript Advanced Programming, Third Edition.

Timer implementation in Node

libuv’s initialization of uv_loop_t type

The previous blog post mentioned that Node will call libuv's uv_run function to start default_loop_ptr for event scheduling. default_loop_ptr points to a variable default_loop_struct of type uv_loop_t. When Node starts, it will call uv_loop_init(&default_loop_struct) to initialize it. The excerpt of uv_loop_init function is as follows:

int uv_loop_init(uv_loop_t* loop) {
 ...
 loop->time = 0;
 uv_update_time(loop);
 ...
}
Copy after login

You can see that the time field of the loop is first assigned a value of 0, and then the uv_update_time function is called, which assigns the latest counting time to loop.time.

After the initialization is completed, default_loop_struct.time has an initial value, and time-related operations will be compared with this value to determine whether to call the corresponding callback function.

libuv’s event scheduling core

As mentioned earlier, the uv_run function is the core part of the libuv library to implement event loop. The following is its flow chart:

Here is a brief description of the above logic related to the timer:

Update the time field of the current loop, which marks the "now" under the current loop concept;

Check whether the loop is alive, that is to say, check whether there are any tasks (handlers/requests) that need to be processed in the loop. If not, there is no need to loop;
Check the registered timers. If the time specified in a timer lags behind the current time, it means that the timer has expired, and its corresponding callback function is executed;
Perform an I/O polling (that is, block the thread and wait for the I/O event to occur). If no I/O is completed when the next timer expires, stop waiting and execute the callback of the next timer.

If an I/O event occurs, the corresponding callback will be executed; since another timer may have expired during the callback execution time, the timer must be checked again and the callback executed.
(Actually (4.) here is more complicated, not just a one-step operation. This description is just to not involve other details and focus on the implementation of the timer.)
Node will keep calling uv_run until the loop is no longer alive.

timer_wrap and timers in Node

There is a TimerWrap class in Node, which is registered as the timer_wrap module inside Node.

NODE_MODULE_CONTEXT_AWARE_BUILTIN(timer_wrap, node::TimerWrap::Initialize)
The TimerWrap class is basically a direct encapsulation of uv_timer_t, and NODE_MODULE_CONTEXT_AWARE_BUILTIN is a macro used by Node to register built-in modules.

After this step, JavaScript can get this module and operate it. The src/lib/timers.js file uses JavaScript to encapsulate the timer_wrap function and exports exports.setTimeout, exports.setInterval, exports.setImmediate and other functions.

Node startup and global initialization

The previous article mentioned that Node will load the execution environment LoadEnvironment(env) when it starts. A very important step in this function is to load src/node.js and execute it. src/node.js will load the specified module And initialize global and process. Of course, functions such as setTimeout will also be bound to the global object by src/node.js.

The above is the entire content of this article, I hope you all like it.

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

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.

How to set a timer on your iPhone camera How to set a timer on your iPhone camera Apr 14, 2023 am 10:43 AM

How long can you set a timer on your iPhone camera? When you access the timer options in the iPhone's camera app, you'll be given the option to choose between two modes: 3 seconds (3s) and 10 seconds (10s). The first option lets you take a quick selfie from the front or rear camera while you're holding your iPhone. The second option is useful in scenes where you can mount your iPhone on a tripod from a distance to click group photos or selfies. How to Set a Timer on an iPhone Camera While setting a timer on an iPhone camera is a fairly simple process, exactly how to do it varies depending on the iPhone model you're using.

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

Learn more about Buffers in Node Learn more about Buffers in Node Apr 25, 2023 pm 07:49 PM

At the beginning, JS only ran on the browser side. It was easy to process Unicode-encoded strings, but it was difficult to process binary and non-Unicode-encoded strings. And binary is the lowest level data format of the computer, video/audio/program/network package

See all articles