About settimeout () chaining calls and setinterval () exploration in JavaScript

Source: Internet
Author: User
Tags time 0

Http://www.cnblogs.com/Wenwang/archive/2012/01/06/2314283.html

Http://www.cnblogs.com/yangjunhua/archive/2012/04/12/2444106.html

The following reference: http://evantre.iteye.com/blog/1718777

1, the origin of the topic

When I was wandering around, I saw a self-answering question:

What are the recommended questions and answers on the front-end development field? , and then what are the classic Web front-end or JavaScript interview pen questions? See the question: What is the difference between the following two sections of code?

(1)

JS Code
    1. SetTimeout ( function () {
    2. / * code block ... * /
    3. SetTimeout (Arguments.callee, 10);
    4. }, 10);


(2)

JS Code
    1. SetInterval ( function () {
    2. / * code block ... * /
    3. }, 10);
2. Long story short

For the problem itself, it does not take much space and time to explain. Simply stated that settimeout () executes a specified function once after a specified time, setinterval () executes a specified function once every other time, and two methods are called timers, not ECMAScript content, but belong to the BOM.

0--x--10, divided into 3 intervals

Here are a few conclusions about this question:

(1) When the timer specifies that the function takes approximately 0ms execution time, the SetTimeout () chain Call and SetInterval () can say that there is no significant difference between the contents of the code block starting every interval 10ms, the time required for each 0ms. (This situation should be rare, or an ideal assumption)

(2) When the timer specifies that the function executes the required time 0 < T < 10ms, the difference between the two is very obvious. Assuming that there are no other tasks in the execution queue, the function specified by the timer can be added to the execution queue at a specified interval and executed immediately, assuming that the timer's specified function execution time requires 5ms,0ms to start executing the timer.

Then for SetTimeout () chaining calls , the function specified in 10ms,settimeout () is added to the execution queue and executed immediately, to 15ms, the code block executes, and a timer is created, then the interval is 10ms at 25ms. The function executes the second time.

For SetInterval (), similarly, at 10ms, thefunction specified by Settinterval () starts executing, and at 15ms, the code block is the specified function, but the next time the function is started will be 20ms. is the interval of 10ms from the time the first execution begins, regardless of the time it takes for the function to execute (of course, the time cannot be greater than 10ms, as previously assumed).

(3) When the timer specifies that the function executes the required time T > 10ms, the difference between the two is also very obvious. Assuming that there are no other tasks in the execution queue, the function specified by the timer can be added to the execution queue at a specified interval and executed immediately, assuming that the timer's specified function execution time requires 20ms,0ms to start executing the timer.

Then for SetTimeout () chaining calls, at 10ms, the function specified by SetTimeout () is added to the execution queue and executed immediately, to 30ms, the code block executes, and a timer is created, then the interval 10ms is at 40ms, the function executes the second time.

For SetInterval (), similarly, at 10ms, the function specified by setinterval () starts executing, and at 30ms time, the code block is the specified function execution, originally according to specify the next time to start executing the function should be 20ms, But here the function execution time has exceeded 20ms, then by the specified, the next time to execute the function should be 30ms, and at this time the function of the first execution is complete, then immediately executes the second time, the result is the first execution, the next start to execute this period there is almost no time interval.

This is where the settimeout () chain Call and SetInterval () are , and the two usages are not meant to be expressed. SetTimeout () The time interval specified by a chained call is the interval between the end of the function's previous execution and the start of the next execution, and thetime specified by S etinterval (), which is the time between the start of the function and the time after the start of execution.

(4) In practical applications, you should choose the right method according to the meaning you want to express, such as if you want to start from a certain moment, every minute of the bell to remind the time, the task each time the execution times need 50ms, this time you should use SetInterval (), The interval is specified as 1 minutes (you change to milliseconds). If you use the settimeout () chain call to specify the same time, the result will be that the first ring time is exactly 0 seconds, but the second ring is 0 seconds plus 50ms (because you are adding a settimeout () timer immediately after the Bell task is completed), Then the result is getting out of your expectation. So I think SetInterval () is more like an alarm clock, while settimeout () is a real timer.

(5) According to Nicholas, it is generally believed that the use of timeout calls to simulate intermittent calls is an optimal mode, in the development environment, very few real intermittent calls are used, because the latter intermittent call may start before the end of the previous intermittent call, but only if there are no other code cases to change the timer, The timer code is added to the queue, and the result may skip some timer code.

3. Practical Analysis

(This paragraph can be skipped) just see this topic when feeling a little bit of impression, but again recall but found that memory is not profound, this also stems from my usual reading not too serious reason, because about this problem in Nicholas's "JavaScript Advanced Programming (Third edition)" There is a more definite explanation in the book. At that time to see this problem is also taken for granted on Google or Baidu, indeed also retrieved a lot of valuable information, such as some of the results will lead me back to Nicholas Book. I believe a lot of people are already familiar with this problem, but there may be a lot of novice will not understand, so I intend to stand on the basis of the predecessors of the settimeout () and SetInterval () of the question of the collection, collation and induction, but also talk about some of their own ideas. At the same time in the Ghost Yi it-Growth Group: 181368696 in the discussion of this issue, the administrator Ann also let me put the issue of the written, so there is a lot of power. And in a step by step practice verification process found that the difference is very obvious, this is a very basic very simple problem, but since also took some time, the process of recording down.

1. Analysis (experiment + theory)

Both SetTimeout () and setinterval () are used to create timers and can implement many functions. Typically, chained calls to SetTimeout () and setinterval () allow the program to repeat a piece of code for a certain interval of time. JavaScript is a single-threaded environment that executes the next piece of code added to the execution queue only when the process is idle, and no code is guaranteed to execute immediately. The time specified by either settimeout () or setinterval () can only ensure that the code specified by the timer is added to the execution queue, not when the code is actually executed. and the timer code specified by settimeout () and setinterval () can only be executed after the function that created it has been completed. Another problem is that the code specified by the timer may take longer than the time interval specified by the timer. The following is a concrete example of how things are going.

(1) In order to test, wrote a delay function, approximate delay of 139ms, specifically as follows

JS Code
    1. function delay () {
    2. The time is added here to test how long this function will be delayed
    3. var start = Date.now (),
    4. End
    5. For (var i = 0; i < 10000; i++) {
    6. For (var j = 0; J < 10000; J + +);
    7. }
    8. End = Date.now ();
    9. Console.log (End-start);
    10. }

Test it with the code below

JS Code
    1. for (var i = 0; i <; ++i) {
    2. Delay ();
    3. }

(This code will block the page when it executes, just for testing) run through multiple tests to take a stable value, the delay time is approximately 139ms (depending on the environment, I am running under the chrome22/win7)




(2) Next use settimeout () Chain Call and SetInterval () respectively to call this delay code, the second parameter is set to 50MS.

First use the settimeout () chain call, the code is as follows

JS Code
  1. function delay () {
  2. For (var i = 0; i < 10000; i++) {
  3. For (var j = 0; J < 10000; J + +);
  4. }
  5. }
  6. var before_time = Date.now (),
  7. After_time,
  8. End
  9. SetTimeout ( function () {
  10. After_time = Date.now ();
  11. var start = After_time;
  12. Console.log (After_time-before_time); //Before starting execution to the next start time interval
  13. Console.log (Start-end); //Previous end to last time interval between start
  14. Before_time = After_time;
  15. Delay ();
  16. End = Date.now ();
  17. SetTimeout (Arguments.callee, 50);
  18. }, 50);

The results of the operation are as follows:




As we expected, 50ms runs between the previous end and the next start. The previous start execution time interval is approximately 210ms, which is slightly larger than the 139ms plus interval 50ms for each time, with some additional overhead.

Now use SetInterval () to look at the code below

JS Code
  1. function delay () {
  2. For (var i = 0; i < 10000; i++) {
  3. For (var j = 0; J < 10000; J + +);
  4. }
  5. }
  6. var before_time = Date.now (),
  7. After_time,
  8. End
  9. SetInterval ( function () {
  10. After_time = Date.now ();
  11. var start = After_time;
  12. Console.log (After_time-before_time); //Before starting execution to the next start time interval
  13. Console.log (Start-end); //Previous end to last time interval between start
  14. Before_time = After_time;
  15. Delay ();
  16. End = Date.now ();
  17. }, 50);

The operation results are as follows




It is clear that there is almost no time interval between the previous end and the next. Since there is no interval, the previous start execution time interval of 140ms, basically equal to the delay () function of each 139ms.

(3) Next use settimeout () Chain Call and SetInterval () respectively to call this delay code, and the difference is the second parameter is set to 200MS.

First look at the settimeout () chain call, the code is still the same as above, just the time to 200ms, the result is as follows




As expected, the interval between the previous end and the next start was 200ms running. The previous start execution time interval is approximately 355ms, slightly greater than 200ms+139ms.

Next look at SetInterval (), the results are as follows




You can see that the previous start execution time interval is exactly the specified 200ms, and the interval between the previous end and the next start is slightly less than 200ms-139ms.

Reference:

"1" Nicholas,javascript Advanced Programming (Third Edition), People's post and Telecommunications press, 2012

"2" Nicholas, high performance JavaScript, electronic industry Press, 2010

    • View Picture Attachments

About settimeout () chaining calls and setinterval () exploration in JavaScript

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.