Node. js advanced programming: using JavaScript to build scalable applications (6) 2.6 core API basics-using timers to develop function execution plans

Source: Internet
Author: User
Document directory
  • Use setTimeout to delay function execution
  • Use clearTimeout to cancel an execution plan
  • Develop and cancel repeated execution plans for Functions
  • Use process. nextTick to delay function execution to the next round of the event Loop
  • Congestion event Loop
  • Exit event Loop
  • Use setTimeout instead of setInterval to ensure the serialization of function execution

For the list of articles in this series and the translation progress, see Node. js advanced programming: using Javascript to build scalable applications (〇)

This article corresponds to the first part of the original article, Chapter 6: Node Core API Basics: Scheduling the Execution of Functions Using Timers

The text is copied from Word here, and the layout is not the same as the original text. You can click here to download the PDF version of this article.

Chapter 6: Using timers to develop the function execution plan this chapter covers:
  • Function Execution Delay
  • Cancel execution plan
  • Develop periodic execution plans for Functions
  • Delay function execution to the next round of the event Loop

 

If you are familiar with client-side JavaScript programming, you may have used the setTimeout and setInterval functions, which allow you to run the functions after a delay of a period of time. For example, the following code, Once loaded to the Web page, will append "Hello there" after the page document in 1 second ":

Var oneSecond = 1000*1; // one second = 1000x1 MS

SetTimeout (function (){

Document. write ('<p> Hello there. </p> ');

}, OneSecond );

SetInterval allows repeated function execution at a specified interval. If the following code is injected into the Web page, a "Hello there" is appended to the page document every second ":

Var oneSecond = 1000*1; // one second = 1000x1 MS

SetInterval (function (){

Document. write ('<p> Hello there. </p> ');

}, OneSecond );

Because Web has already become a platform for building applications, instead of simple static pages, this kind of requirement is increasingly emerging. These task scheduler functions help developers implement regular form verification, delay remote data synchronization, or UI interaction that requires delayed response. Node also fully implements these methods. On the server side, you can use them to repeat or delay the execution of many tasks, such as cache expiration, connection pool cleanup, session expiration, and polling.

Use setTimeout to delay function execution

SetTimeout can be used to create an execution plan for running a specified function at a certain time in the future. For example:

Var timeout_ms = 2000; // 2 seconds

Var timeout = setTimeout (function (){

Console. log ("timed out! ");

}, Timeout_ms );

Like JavaScript on the client side, setTimeout accepts two parameters. The first parameter is the function to be delayed, and the second parameter is the delay time (in milliseconds ).

SetTimeout returns a timeout handle, which is an internal object and can be used as a parameter to call clearTimeout to cancel the timer. In addition, this handle has no effect.

Use clearTimeout to cancel an execution plan

Once a timeout handle is obtained, clearTimeout can be used to cancel the function execution plan, as shown in the following code:

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 "time out!" will be output !" These words. You can also cancel the execution plan at any time in the future, as shown in the following example:

Var timeout = setTimeout (function (){

Console. log ("timed out! ");

},2000 );

SetTimeout (function B (){

ClearTimeout (timeout );

},1000 );

The Code specifies two delayed execution functions A and B. function A is scheduled to be executed after 2 seconds, and function B is scheduled to be executed after 1 second, because function B is executed first, it cancels the execution plan of A, so A will never run.

Develop and cancel repeated execution plans for Functions

SetInterval is similar to setTimeout, But it repeats a function at a specified interval. You can use it to periodically trigger a program to complete other tasks that need to be repeated, such as cleanup, collection, logs, data retrieval, and polling.

The following code outputs "tick" to the console every second ":

Var period = 1000; // 1 second

SetInterval (function (){

Console. log ("tick ");

}, Period );

If you don't want it to run forever, you can use clearInterval () to cancel the timer.

SetInterval returns an execution plan handle, which can be used as the clearInterval parameter to cancel the execution plan:

Var interval = setInterval (function (){

Console. log ("tick ");

},1000 );

//...

ClearInterval (interval );

Use process. nextTick to delay function execution to the next round of the event Loop

Sometimes the client JavaScript programmer uses setTimeout (callback, 0) to delay the task for a short period of time, the second parameter is 0 milliseconds, it tells the JavaScript runtime, this callback function is executed immediately after all pending events are processed. Sometimes this technique is used to delay the execution of operations that do not need to be executed immediately. For example, you may need to play an animation or perform other calculations after the user event is processed.

In Node, it is like the literal meaning of "event loop". An event loop runs in a loop that processes the event queue. Every round of the event loop is called a tick.

You can call the callback function once every time the next round (next tick) of execution in the event loop, which is exactly process. the principle of nextTick, while setTimeout and setTimeout use the internal execution queue during JavaScript runtime, rather than the event loop.

By using process. nextTick (callback) instead of setTimeout (callback, 0). Your callback function will be executed immediately after the events in the queue are processed, it is much faster than the JavaScript timeout Queue (measured by CPU time ).

You can delay the function to the next event loop and then run it as follows:

Process. nextTick (function (){

My_expensive_computation_function ();

});

Note: processThe object is Node.One of the few global objects.

Congestion event Loop

Node and JavaScript use a single-thread event loop to process the next event in the queue. When the event execution is complete, the event loop gets the execution result and processes the next event. This is repeated until the event queue is empty. If one of the callback functions takes a long time to run, the event loop cannot process other suspended events during that period, which slows down the application or service.

When processing an event, if a memory-sensitive or processor-sensitive function is used, the event loop slows down, and a large number of events are accumulated, so the event cannot be processed in time or even blocked in the queue.

The following is an example of blocking event loops:

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 );

In this example, the nextTick2 and timeout functions do not run as long as they are waiting, because the event loop is blocked by the infinite loop in the nextTick function, even if the timeout function is scheduled to run in 1 second, it will not run.

When setTimeout is used, the callback functions are added to the execution plan queue. In this example, they are not even added to the queue. This is an extreme example, but you can see that running a processor-sensitive task may block or slow down the event loop.

Exit event Loop

Use process. nextTick can postpone a non-critical task to the next round (tick) of the event loop, so that it can release the event loop and continue to execute other suspended events.

Let's take a look at the following example. If you want to delete a temporary file but do not want the data Event Callback Function to wait for this IO operation, you can delay it like this:

Stream. on ("data", function (data ){

Stream. end ("my response ");

Process. nextTick (function (){

Fs. unlink ("/path/to/file ");

});

});

Use setTimeout instead of setInterval to ensure the serialization of function execution

Assume that you want to design a function named my_async_function, which can perform some I/O operations (such as parsing log files) and periodically execute it, you can use setInterval to implement it like this:

Var integer = 1000;

SetInterval (function (){

My_async_function (function (){

Console. log ('My _ async_function finished! ');

});

}, Interval);//Note: I added the bold part above, and the author should have omitted it by mistake.

You must ensure that these functions are not executed at the same time, but you cannot guarantee this if setinterval is used. If the my_async_function function runs for a millisecond longer than the interval variable, they will be executed at the same time, rather than in serial order.

Note:(The bold part below is added to the translator, not the original book content)

To facilitate understanding of this part of content, you can modify the author's Code so that it can actually run:

Var integer = 1000;

SetInterval (function (){

(Function my_async_function (){

SetTimeout (function (){

Console. log ("1 ");

},5000 );

})();

}, Interval );

Run this code to see, you will find, wait for 5In seconds"Every 1Output once in seconds. We expect that the current my_async_functionExecution completed (5Seconds), wait for 1Second and then execute the next my_async_functionThe interval between each output is 6.Seconds. This is becauseMy_async_functionInstead of serial execution, multiple instances are running simultaneously.

Therefore, you need a way to force the interval between the execution of a my_async_function and the execution of the next my_async_function is exactly the time specified by the interval variable. You can do this:

Var interval = 1000; // 1Seconds

 

(Function schedule (){//3rdLine

SetTimeout (function do_it (){

My_async_function (function (){//5thLine

Console. log ('async' is done! ');

Schedule ();

});

}, Interval );

}());//10thLine

In the previous code, a function called schedule (row 3rd) is declared and called immediately after the declaration (row 10th). The schedule function will be within 1 second (specified by interval) and then run the do_it function. After one second, the my_async_function of Line 1 will be called. After it is executed, it will call its own anonymous callback function (Row 3 ), the anonymous callback function will reset the do_it execution plan again, so that it can be re-executed in one second, so that the Code starts to be executed in a serial loop.

Summary

You can use the setTimeout () function to pre-set the function execution plan and use the clearTimeout () function to cancel it. You can also use setInterval () to repeatedly execute a function. Correspondingly, you can use clearInterval () to cancel this execution plan.

If an event loop is blocked due to a processor-sensitive operation, the functions that were originally intended to be executed will be delayed and will never be executed. Therefore, do not use CPU-sensitive operations in the event loop. Also, you can use process. nextTick () to delay function execution to the next round of the event loop.

When I/O and setInterval () are used together, you cannot guarantee that there is only one pending call at any time point. However, you can use recursive functions and setTimeout () function to avoid this tricky problem.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.