When setTimeout () and setInterval () are called and executed in Js

Source: Internet
Author: User

Definition
SetTimeout () and setInterval () are often used to process latency and scheduled tasks. The setTimeout () method is used to call a function or computing expression after a specified number of milliseconds, while setInterval () can call a function or expression cyclically at a specified number of milliseconds, until clearInterval clears it.
From the definition, we can see that the two functions are very similar, except that the former is executed once, while the latter can be executed multiple times, and the parameters of the two functions are the same, the first parameter is the code or handle to be executed, and the second parameter is the number of milliseconds of delay.
It is easy to define and use, but sometimes our code is not called according to our imagination, which is confusing.

Simple Example
Let's look at a simple example. After loading a simple page for two seconds, write Delayed alert!

Copy codeThe Code is as follows: setTimeout ('document. write ("Delayed alert! ");", 2000 );

It looks reasonable. Let's look at another example of the setInterVal () method.Copy codeThe Code is as follows: var num = 0;
Var I = setInterval (function (){
Num ++;
Var date = new Date ();
Document. write (date. getMinutes () + ':' + date. getSeconds () + ':' + date. getMilliseconds () + '<br> ');
If (num> 10)
ClearInterval (I );
},1000 );

The page records the current time every one second (Minutes: seconds: milliseconds). After 10 records are recorded, the page is cleared and no longer recorded. Considering that the code execution time may not be the execution time, but the interval should be the same, let's look at the results.Copy codeThe Code is as follows: 38: 116
: 39: 130
: 40: 144
: 41: 158
: 42: 172
: 43: 186
: 44: 200
: 45: 214
: 46: 228
: 47: 242
: 48: 256

Why?
The interval is almost 1000 milliseconds, but not accurate. Why? The reason is that we have a misunderstanding about the JavaScript timer. JavaScript is actually running in a single-threaded environment, which means that the timer only schedules code execution at a certain time in the future, the specific execution time cannot be guaranteed, because other code may be used to control the JavaScript process at different times during the lifecycle of the page. After the page is downloaded, the code running, event handler, and Ajax callback functions all use the same thread. In fact, the browser is responsible for sorting and assigning the priority of running a program at a certain time point.
Let's zoom in to see how to add a time-consuming task.Copy codeThe Code is as follows: function test (){
For (var I = 0; I <500000; I ++ ){
Var div = document. createElement ('div ');
Div. setAttribute ('id', 'testdiv ');
Document. body. appendChild (div );
Document. body. removeChild (div );
}
}
SetInterval (test, 10 );
Var num = 0;
Var I = setInterval (function (){
Num ++;
Var date = new Date ();
Document. write (date. getMinutes () + ':' + date. getSeconds () + ':' + date. getMilliseconds () + '<br> ');
If (num> 10)
ClearInterval (I );
},1000 );

We added another scheduled task to check the result.Copy codeThe Code is as follows: 9: 222
: 12: 482
: 16: 8
: 19: 143
: 22: 631
: 25: 888
28: 712
: 32: 381
: 34: 146
: 35: 565
: 37: 406

The effect is obvious, the gap is even more than 3 seconds, and the gap is inconsistent.
We can think of JavaScript as running on a time line. When a page is loaded, the method and variable declaration and data processing used after the page lifecycle are first executed. After that, the JavaScript process will wait for more code to be executed. When the process is idle, the next code is triggered.

In addition to the main JavaScript process, you also need a code queue that is executed when the process is idle for the next time. As the page lifecycle goes on, the code will be added to the queue in the execution order. For example, when the button is pressed, its event handler will be added to the queue, and execute it within the next possible time. When an Ajax response is received, the callback function code is added to the queue. No code in JavaScript is executed immediately, but it is executed as soon as the process is idle. The timer works on the queue by inserting the code after a specific time, which does not mean that it will be executed immediately and can only be executed as soon as possible.
After knowing this, we can understand that if you want precise time control, you cannot rely on the setTimeout Function of JavaScript.

Repeated Timer
The timer created by setInterval () can be used to execute the code cyclically. You can clear the interval when the specified effect is available, as shown in the following example.Copy codeThe Code is as follows: var my_interval = setInterval (function (){
If (condition ){
//..........
} Else {
ClearInterval (my_interval );
}
},100 );

However, the problem with this method is that the timer Code may not be executed until the code is added to the queue again. As a result, the judgment conditions in the loop are inaccurate and the code is executed several times, there is no pause between them. However, JavaScript has solved this problem. When setInterval () is used, the timer code is inserted into the queue only when other code instances without the timer are used. This ensures that the minimum interval between the timer code and the queue is the specified interval.

Such a rule brings two problems

1.1. Certain intervals will be skipped
2. The interval between code execution of multiple timers may be smaller than expected
To avoid these two drawbacks, we can use setTimeout () to implement repeated timers.Copy codeThe Code is as follows: setTimeout (function (){
// Code
SetTimeout (arguments. callee, interval );
}, Interval)

In this way, a new timer will be created for each function execution. The second setTimeout () call uses agrument. callee to obtain the reference of the currently implemented function and set another timer. In this way, no new timer is inserted before the code execution is complete, and at least a specified time interval must be specified before the next timer code execution to avoid continuous operation.Copy codeThe Code is as follows: setTimeout (function (){
Var div = document. getElementById ('movev ');
Var left = parseInt (div. style. left) + 5;
Div. style. left = left + 'px ';
If (left <200 ){
SetTimeout (arguments. callee, 50 );
}
}, 50 );

This timer code moves a div 5px to the right each time it is executed, and stops when the coordinates exceed 200.

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.