JavaScript Timer principle Analysis

Source: Internet
Author: User

Tag: Time () No State defines how many console functions the size page

The timer in JavaScript everyone has met in the normal development, but how many people to deeply understand the principle of it? Let's analyze the implementation principle of the timer.

I. Knowledge of reserves

In the project we will generally meet the two kinds of timers, the first is settimeout, the second is setinterval, the two timers as the difference:

1, SetTimeout allows to set a timeout object, time-out after executing this object, but only once, no cycle

2, Setinternval allows to set a timeout object, after time-out to execute the object, the period is equal to the time specified by the timeout object, the cycle is infinite loop

Give a simple example to illustrate:

<!DOCTYPE HTML><HTMLLang= "en"><Head>    <MetaCharSet= "UTF-8">    <title>Blog case</title></Head><Body>    <Scripttype= "Text/javascript">SetTimeout ("alert (' This is test ')", -); SetInterval ("Console.log (' demo ');", +); </Script></Body></HTML>

The result of this run is a popup dialog, and then the console can see the output of the demo word every 1 seconds.

Second, the timer principle first knowledge

So the question arises, what happens when the code is running?

<! DOCTYPE html>        setTimeout ("alert (' Timer! ') ", 0);        Alert ("test")    </script></body>

is the alert ("test") performed first, or the alert ("Timer") executed first, then let's run it!

After running the result is to pop up the test words pop-up box, and then pop up the timer word pop-up box, why this? is not the timer time of 0 can be executed?

The answer is not, because JS is known to be single-threaded, so a lot of people will think in the above example will block the waiting timer to execute after the execution of the following statement, but this is one of the single-threaded one, in order to solve this problem, the introduction of asynchronous mechanism. The asynchronous mechanism mainly uses a knowledge point that we seldom pay attention to--the multi-threading of the browser. What exactly is a multi-threaded browser?

third, multi-threaded browser

Here we have to explain, it is well known that JS is single-threaded, but for the browser to the implementation of JS is only a large number of browsers out of the box, we call the JS engine thread. The other threads of the browser are the corresponding threads that are assigned to the browser by the JS engine thread after executing to a specific function. The specific principles are described in the illustration:

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

Let's look at the following code to 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 popup box for testing, and then because the timer time is 0, Therefore, the execution timer thread will be able to add the task of the popup timer to the main thread (JS engine thread) queue, wait for the JS engine call, this time we see the result is to pop the test first, and then pop the timer

In addition, we have to note that in the HTML5 specification timer timing time can not be less than 4ms, if it is less than 4ms, 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 generally in the project is not what impression, This is just an understanding.

OK, we'll rewrite the code above, and then we'll look at the effect:

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

The results after the run are as follows:

Here are a few points of knowledge:

1. Console.time and Console.timeend are two ways to get the time spent executing statements between them, we can know that test execution time is around 1ms, but the timer time is around 1000ms, so these two statements can only calculate the current engine execution time, in other words is the runtime of the timer module in the browser is so impossible to calculate

2, in addition we can see a phenomenon is that the timer in the execution of the time is not 1000 timers are printed out at once, 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 is not executed?

As we said above is the time of the timer, the task will be added to the JS engine thread, regardless of whether the statement inside the task is completed, will be like the JS engine thread queue to add, but the rest of the completion of the statement to do?

When the program executes to the timer task, it first loads the statements that have already been executed in the timer module and then resumes execution of the remaining statements of the timer module. (the task that the Timer module adds to the JS engine is a pointer to the C language, pointing to the timer module)

So, settimeout we can define as:

Within the 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 use method is directly when a loop timer is used, here is not an example of

For SetInterval (FN, 100) It is easy to create a misunderstanding: not the last time the FN was executed, the next FN will start after 100ms. In fact, setinterval and regardless of the last FN execution results, but every 100ms will put the FN into the main thread queue, and two times between the specific interval between FN is not necessarily, and settimeout actual delay time is similar, and JS implementation of the situation. The specific delay effect is related to memory and other factors.

Five, the reliability of the timer

Although timers tend to stabilize in most cases, there are some errors when using the timer.

As shown below:

<script type= "Text/javascript" >     varnew  Date (). GetTime ();     SetInterval (function() {         varnew  Date (). GetTime ();         Console.log ("setinterval Execution Difference Time:" + (time2-time1))     ;     </script>

The results of the operation are as follows:

We can see the timer there are some small errors, such as the first time the run time of 1001ms than we set the time to more than 1ms, so concluded: The timer is not completely reliable, there is a very small error . This is still in the Chrome browser test results, in the IE browser test that?

The results show that the error is greater under IE browser

Six, the magic of the timer

Timers can also be used to optimize time-consuming code in the project, in addition to being a timed function:
we assume that there is a scenario, that is, in a page to render 500,000 nodes, this time for the general project, the direct rendering is not desirable, because this time will occupy too much memory, causing the browser to become stuck in the state, the user mistakenly think that the page is 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 we have to solve the problem, we can use the timer to optimize the problem first we can divide 500,000 nodes into groups, each group renders not too many nodes, Then through the setinterval to cycle this does not block the operation of the JS engine thread, and can not improve the time spent rendering. So that the final optimized rendering is achieved.

Seven, timer use precautions

If there is a timer involved in the project then remember to call Clearinterval or cleartimeout when a timer is executed to clear the timer, so as not to interfere with the timer between the phenomenon of some scratching

JavaScript Timer principle Analysis

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.