


Detailed explanation of using timers to execute functions regularly in Node.js_node.js
If you are familiar with client-side JavaScript programming, you may have used the setTimeout and setInterval functions, which allow a delay in running a function for a period of time. For example, the following code, once loaded into the web page, will append "Hello there" to the page document after 1 second:
var oneSecond = 1000 * 1; // one second = 1000 x 1 ms
setTimeout(function() {
document.write('
Hello there.
');}, oneSecond);
And setInterval allows the function to be executed repeatedly at specified intervals. If the following code is injected into a Web page, it will cause "Hello there" to be appended to the page document every second:
var oneSecond = 1000 * 1; // one second = 1000 x 1 ms
setInterval(function() {
document.write('
Hello there.
'); }, oneSecond);
Because the Web has long become a platform for building applications, rather than simple static pages, this kind of similar demand is increasingly emerging. These task scheduling functions help developers implement periodic form validation, delayed remote data synchronization, or UI interactions that require delayed responses. Node also fully implements these methods. On the server side, you can use them to repeat or delay many tasks, such as cache expiration, connection pool cleanup, session expiration, polling, etc.
Use setTimeout delay function to execute
setTimeout can formulate an execution plan to run the specified function once in the future, such as:
var timeout_ms = 2000; // 2 seconds
var timeout = setTimeout(function() {
console.log("timed out!");
}, timeout_ms);
Exactly the same as client-side JavaScript, setTimeout accepts two parameters. The first parameter is the function that needs to be delayed, and the second parameter is the delay time (in milliseconds).
setTimeout returns a timeout handle, which is an internal object. You can use it as a parameter to call clearTimeout to cancel the timer. Otherwise, this handle has no effect.
Use clearTimeout to cancel the execution plan
Once you obtain the timeout handle, you can use clearTimeout to cancel the function execution plan, like this:
var timeoutTime = 1000; // one second
var timeout = setTimeout(function() {
console.log("timed out!");
}, timeoutTime);
clearTimeout(timeout);
In this example, the timer will never be triggered, nor will the words "time out!" be output. You can also cancel the execution plan at any time in the future, as in the following example:
var timeout = setTimeout(function A() {
console.log("timed out!");
}, 2000);
setTimeout(function B() {
}, 1000);
Make and cancel repeated execution plans for functions
setInterval is similar to setTimeout, but it will execute a function repeatedly at specified intervals. You can use it to periodically trigger a program to complete tasks such as cleaning, collection, logging, data acquisition, polling, etc. that need to be performed repeatedly.The following code will output a "tick" to the console every second:
setInterval(function() {
console.log("tick");
}, period);
setInterval returns an execution plan handle, which can be used as a parameter of clearInterval to cancel the execution plan:
console.log("tick");
}, 1000);
// …
clearInterval(interval);
Use process.nextTick to delay function execution until the next round of the event loop
Sometimes client-side JavaScript programmers use setTimeout(callback,0) to delay the task for a short period of time. The second parameter is 0 milliseconds, which tells the JavaScript runtime to wait immediately after all pending events have been processed. Execute this callback function. Sometimes this technique is used to delay the execution of operations that do not need to be performed immediately. For example, sometimes you need to start playing animation or do some other calculations after the user event is processed.
In Node, just like the literal meaning of "event loop", the event loop runs in a loop that processes the event queue. Each round of the event loop's work process is called a tick.
You can call the callback function once every time the event loop starts the next round (next tick) of execution. This is exactly the principle of process.nextTick, and setTimeout and setTimeout use the execution queue inside the JavaScript runtime, and Not using event loop.
By using process.nextTick(callback) instead of setTimeout(callback, 0), your callback function will be executed immediately after the event in the queue is processed, which is much faster than JavaScript's timeout queue (in CPU time to measure).
You can delay the function until the next round of the event loop as follows:
process.nextTick(function() {
my_expensive_computation_function();
});
Note: The process object is one of the few global objects in Node.
Blocking the event loop
The runtime of Node and JavaScript uses a single-threaded event loop. Each time it loops, the runtime processes the next event in the queue by calling the relevant callback function. When the event is executed, the event loop obtains the execution result and processes the next event, and so on until the event queue is empty. If one of the callback functions takes a long time to run, the event loop will not be able to handle other pending events during that time, which can make the application or service very slow.
When processing events, if memory-sensitive or processor-sensitive functions are used, the event loop will become slow, and a large number of events will accumulate, which cannot be processed in time, or even block the queue.
Look at the following example of blocking the event loop:
process.nextTick(function nextTick1() {
var a = 0;
while(true) {
a ;
}
});process.nextTick(function nextTick2() {
console.log("next tick");
});
setTimeout(function timeout() {
console.log("timeout");
}, 1000);
When using setTimeout, the callback functions will be added to the execution plan queue, and in this example they will not even be added to the queue. This is an extreme example, but you can see that running a processor-intensive task can block or slow down the event loop.
Exit the event loop
Using process.nextTick, you can postpone a non-critical task to the next round (tick) of the event loop, which releases the event loop so that it can continue to execute other pending events.Look at the example below. If you plan to delete a temporary file, but don’t want the callback function of the data event to wait for this IO operation, you can delay it like this:
stream.end("my response");
process.nextTick(function() {
fs.unlink("/path/to/file");
});
Suppose you plan to design a function called my_async_function, which can perform certain I/O operations (such as parsing log files), and intend to let it execute periodically. You can use setInterval to implement it like this:
var interval = 1000;
setInterval(function() {
my_async_function(function() {
console.log('my_async_function finished!');
},interval);//Translator’s Note: The previous “,interval” was added by me, the author may have omitted it due to a typographical error
Translator’s Note: (The bolded parts below are added by the translator and are not the content of the original book)
In order to facilitate the understanding of this part of the content, you can modify the author's code so that it can actually run:
setInterval(function(){
(function my_async_function(){
setTimeout(function(){
console.log("1");
},5000);
},interval);
Run this code and take a look. You will find that after waiting for 5 seconds, "hello" is output every 1 second. Our expectation is that after the current my_async_function is executed (it takes 5 seconds), wait for 1 second before executing the next my_async_function. There should be an interval of 6 seconds between each output. This result is caused by the fact that my_async_function is not executed serially, but multiple ones are running at the same time.

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.

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

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver CS6
Visual web development tools