How javascript timers work

Source: Internet
Author: User
Speaking of the timer in javascript, we will certainly think of the setTimeout () and setInterval () functions. This article analyzes the working principle and difference of the two from the perspective of EventLoop. Speaking of the timer in javascript, we will certainly think of the setTimeout () and setInterval () functions. This article analyzes the working principle and difference of the two from the perspective of Event Loop.

SetTimeout ()

MDN defines setTimeout as follows:

Call a function or execute a code snippet after the specified delay.

Syntax

The setTimeout syntax is very simple. The first parameter is the callback function, and the second parameter is the delay time. The function returns a unique identifier of the value type. This ID can be used as a clearTimeout parameter to cancel the Timer:

Var timeoutID = window. setTimeout (code, delay );

IE0 + also supports callback parameter input:

Var timeoutID = window. setTimeout (func, delay, [param1, param2,...]);

SetInterval ()

MDN defines setInterval as follows:

Periodically call a function or execute a piece of code.

Because setInterval and setTimeout are used in the same way, they are not listed here.

Description of the second parameter (delay)

Because of the javascript event Loop Mechanism, the second parameter does not mean to execute the callback function immediately after delay milliseconds, but to add the callback function to the event queue. In fact, there are differences between setTimeout and setInterval:

SetTimeout: After the delay of delay is milliseconds, the callback function is directly added to the event queue.

SetInterval: After the delay of delay is milliseconds, first check whether there is a callback function in the event queue that has not been executed (setInterval callback function). If yes, do not add callback functions to the event queue.

Therefore, when there are time-consuming tasks in our code, the timer does not behave as we think.

Use an example to understand

The following code is intended to call the callback function in 100 ms and 200 ms (that is, just waiting for 100 ms:

Var timerStart1 = now ();
SetTimeout (function (){
Console. log ('wait time for the first setTimeout callback execution: ', now ()-timerStart1 );

Var timerStart2 = now ();
SetTimeout (function (){
Console. log ('second setTimeout callback execution wait time: ', now ()-timerStart2 );
},100 );
},100 );
// Output:
// The first setTimeout callback execution wait time: 106
// The second setTimeout callback execution wait time: 107

This result seems exactly what we think, but once we add time-consuming tasks to the Code, the results are not as expected:

Var timerStart1 = now ();
SetTimeout (function (){
Console. log ('wait time for the first setTimeout callback execution: ', now ()-timerStart1 );

Var timerStart2 = now ();
SetTimeout (function (){
Console. log ('second setTimeout callback execution wait time: ', now ()-timerStart2 );
},100 );

HeavyTask (); // time-consuming task
},100 );

Var loopStart = now ();
HeavyTask (); // time-consuming task
Console. log ('heavytask time consumed: ', now ()-loopStart );

Function heavyTask (){
Var s = now ();
While (now ()-s <1000 ){
}
}

Function now (){
Return new Date ();
}
// Output:
// HeavyTask time consumption: 1015
// The first setTimeout callback execution wait time: 1018
// The second setTimeout callback execution wait time: 1000

The two setTimeout wait events are no longer 100 ms because time-consuming tasks exist! Let's describe the process:

First, the execution of the first time-consuming task (heavyTask () takes about 1000 ms.

The time-consuming task starts to run. After 100 ms, the first setTimeout callback function is expected to be executed. Therefore, it is added to the event queue, but the previous time-consuming task has not been completed yet, therefore, it can only wait in the queue until the time-consuming task has been executed. Therefore, we can see in the result that the first setTimeout callback execution wait time is 1018.

The first setTimeout callback is executed, and the second setTimeout is enabled. This timer is also expected to be able to execute its callback function after 100 ms delay. However, there is another time-consuming task in the first setTimeout. The plot of this task is the same as that of the first timer, and it takes 1000 ms to start execution.

The following figure can be used for generalization:

Summary

This section briefly analyzes the principle of javascript timer execution and hopes to help us better understand javascript. Some improper descriptions can be pointed out in the comments.

For more articles about how javascript timers work, please follow the PHP Chinese network!

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.