The principle analysis of JavaScript timer implementation _javascript Skill

Source: Internet
Author: User
Tags setinterval

JavaScript in the timer everyone basically in peacetime development have met it, but how many people to deeply understand the principle of it? Here we will analyze the implementation of the timer principle.

I. Reserve knowledge

In our project, we usually meet the two kinds of timers, the first is settimeout, the second is setinterval, the two kinds of timers like the following difference:

1. settimeout allows you to set a timeout object that executes this object after a timeout, but only once, without cycles

2, Setinternval allows to set a timeout object, the timeout after the execution of this object, the cycle is equal to the timeout object specified time, cycle is infinite loop

Give a simple example to illustrate:

<! DOCTYPE html>
 
 

The result of this run is a pop-up dialog, and then at the console you can see the demo in every 1 seconds.

Second, the first knowledge of the timer principle

So the question is, what happens when the next code runs?

<! DOCTYPE html>
 
 

Whether to execute alert ("test") first or to execute alert ("Timer"), then let's run it!

After running the result is to pop the test words pop-up box, and then pop-up timer words pop-up box, why this? is not the timer time is 0 to be able to execute?

This is not the answer, because JS is known to be single-threaded, so many people think that in the above example will block waiting for the execution of the timer before executing the following statement, but this is one of the single thread of the flaw, in order to solve this problem, introduced an asynchronous mechanism. Asynchronous mechanism is mainly to take advantage of a little we usually pay attention to a knowledge point-multithreading of the browser. What exactly is a browser multithreading it?

Third, the browser multithreading

Here we will explain, as we all know, JS is single-threaded, but for browsers, the implementation of JS is only in the browser many ready-made one, we call the JS engine thread. Other threads in the browser are the corresponding threads that are assigned to the browser through the JS engine thread after performing to a particular function. The detailed principle is detailed in the diagram:

From this picture we can know that the JS engine thread executes the callback function block first, then executes the Click event callback, then executes the timer thread, and finally executes the other thread.

In the following code we analyze:

SetTimeout ("Alert (' Timer! ')", 0);
Alert ("Test")

First JS thread read to the settimeout timer, this time will execute the browser thread, and then skip the timer to continue execution, this time you will see the contents of the pop-up box for testing, and then because the timer time is 0, So a timer thread will be able to the pop-up box for the task of the word timer added to the main thread (JS engine thread) after the queue, waiting for the JS engine call, this time we see the result is the first pop-up test, and then pop-up timer

In addition, we should note that in the HTML5 specification the timer can not be less than 4ms time, if it is less than 4ms, then the default is 4ms, so in this example 0, the default is 4ms, but this in the browser does not pass the performance is different, but this is generally in the project is not what the impression, This is only to understand.

Okay, we'll rewrite the code above so we can look at the effect:

 <script type= "Text/javascript" >
  console.time ("test");
  SetTimeout ("for (Var i=0;i<1000;i++) console.log (' Timer! ');", 1000);
  Console.log ("test");
  Console.timeend ("test");
 </script>

The results of the run are as follows:

Here are a few points of knowledge:

1, Console.time and Console.timeend The two methods are the time to get the statements executed between them, from the graph we can know that the test execution time is around 1ms, but the timer timing is around 1000ms so these two statements can only calculate the current engine execution time, in other words In other words, the timer module in the browser is running in such a way that it can't be counted.

2, in addition we can see a phenomenon is the timer in the implementation of the time is not 1000 timers are all one-time print out, but hundreds of hundreds of increase, this is why? Here's another question, if it's time for the timer, but what happens when the task in the timer doesn't execute?

We said above is the timer time to the case, will be added to the JS engine thread task, regardless of the task inside the statement is completed, will be like the JS engine thread queue to add, but the rest of the unfinished execution of the statement to do?

When the program executes the timer task, it first loads the statements already executed in the Timer module and then continues to execute the remaining statements of the timer module. (The timer module to the JS engine to add the task is equivalent to a pointer in C language, pointing to the timer module)

So, settimeout we can define as:

Within a specified time, the task is placed in the event queue, waiting for the JS engine to be idle and executed.

Iv. Use of SetInterval

SetInterval the most basic way to use is directly when a loop timer used, here is not an example

For SetInterval (FN, 100) It is easy to create an erroneous zone: it is not the last FN after the implementation of the 100ms before the next FN began to execute. In fact, setinterval and regardless of the last FN execution results, but every 100ms to put FN into the main thread queue, and two times between the exact interval between FN is not necessarily, with settimeout actual delay time, and JS performance. The specific latency effect is related to memory and other factors.

Five, the reliability of the timer

Although timers tend to be stable in most cases, there are also some errors in the use of timers.

As shown below:

<script type= "Text/javascript" >
  var time1 = new Date (). GetTime ();
  SetInterval (function () {
   var time2 = new Date (). GetTime ();
   Console.log ("The difference Time of setinterval execution:" + (TIME2-TIME1));
  },1000);
 </script>

The results of the operation are as follows:

From the diagram we can see that there are some small errors in the timer, such as the first run time of 1001ms more than we set the time out of 1ms, so come to the conclusion: the timer is not completely reliable, there is a very small error. This is still the results of the test in the Chrome browser, in exchange for the Internet Explorer test so what?

The results show that the error is greater under IE browser

Six, the magical uses of the timer

In addition to being timed, timers can be used to optimize time-consuming code in a project:

We assume that there is such a scenario, is in a page to render 500,000 nodes, this time for the general project, direct rendering is not desirable, because this time will occupy too much memory, resulting in the browser card dead state, the user mistakenly thought is the page card dead and directly close the browser or kill the process, Even if the user does not close the page so that the user experience is not good, this time how do we solve this problem, we can use the timer to optimize the problem first we can divide 500,000 nodes into groups, each set of the number of nodes to render not too much, And then through the setinterval to loop this does not block the JS engine thread running, but also can not improve the rendering consumption time. In order to achieve the final optimization rendering.

Seven, the timer uses the attention matters

If there's a timer involved in the project then remember to call the Clearinterval or cleartimeout to clear the timer at the end of a timer, lest the timer interfere with each other.

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, if there are questions you can message exchange, but also hope that a lot of support cloud Habitat community!

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.