How to implement a JavaScript timer

Source: Internet
Author: User
Tags set time setinterval

The timer in JavaScript has basically been met in normal development, but how many people have gone into depth to understand the principle? Next we will analyze the implementation principle of the timer.

I. Reserve knowledge

In our project, we generally encounter two types of timers: setTimeOut and setInterval, which have the following differences:

1. setTimeout allows you to set a time-out Object. This object is executed only once after the time-out period.

2. setInternval allows you to set a timeout object. This object is executed after the timeout. The period is equal to the time specified by the timeout object, and the period is an infinite loop.

Here is a simple example:

<! DOCTYPE html>

<Html lang = "en">

<Head>

<Meta charset = "UTF-8">

<Title> blog case </title>

</Head>

<Body>

<Script type = "text/javascript">

SetTimeout ("alert ('this is test')", 2000 );

SetInterval ("console. log ('demo');", 1000 );

</Script>

</Body>

</Html>

After this operation, a dialog box is displayed, and the demo is displayed every second on the console.

II. Initial knowledge of timer principles

The problem arises. What happens when the following code is running?

<! DOCTYPE html>

<Html lang = "en">

<Head>

<Meta charset = "UTF-8">

<Title> blog case </title>

</Head>

<Body>

<Script type = "text/javascript">

SetTimeout ("alert ('timer! ') ", 0 );

Alert ("test ")

</Script>

</Body>

</Html>

Execute alert ("test") first, or execute alert ("timer") first, so let's run it!

The result after running is that the pop-up box with the test text is displayed, and then the pop-up box with the timer text is displayed. Why? Can the timer be executed if its time is 0?

This is not the answer, because JS is well known as a single thread, so many people think that in the above example, the following statement will be executed after the timer is executed successfully, but this is one of the defects of a single thread. To solve this problem, an asynchronous mechanism is introduced. The asynchronous mechanism mainly utilizes a knowledge point that we seldom pay attention to at ordinary times-browser multithreading. What is the multithreading of the browser?

3. Multithreading of browsers

As we all know, JavaScript is single-threaded, But JavaScript execution is only one of the many ready-made browsers, which we call a JS engine thread. Other threads of the browser are the corresponding threads designated to the browser after the JS engine thread executes a specific function. For detailed principles, see the figure below:

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

The following code is analyzed:

SetTimeout ("alert ('timer! ') ", 0 );

Alert ("test ")

First, the JS thread reads the setTimeout timer. At this time, the browser thread will be executed, and the timer will be skipped to continue execution. At this time, you will see the content in the pop-up box as a test, then, because the timer time is 0, when the timer thread is executed, the task with the word "timer" in the pop-up box can be added to the queue of the main thread (JS engine thread, wait for the JS engine to call. At this time, we can see that the test is popped up first, and then the timer is popped up.

In addition, we should note that the timer time in the HTML5 specification cannot be less than 4 ms. If it is less than 4 ms, the default time is 4 ms. Therefore, in this example, 0, the default value is 4 ms, but the performance in browsers that do not pass is different, but this is generally not impressive in the project, this is just to understand.

Okay, let's rewrite the above code to this, and then let's take a 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 running result is as follows:

Here are some knowledge points:

1. console. time and console. the timeEnd method can be used to obtain the time used to execute the statement in the middle of the statement. From the figure, we can know that the test execution time is about 1 ms, however, the timer time is about MS, so the two statements can only calculate the execution time of the current engine. In other words, the running time of the timer module in the browser cannot be calculated.

2. In addition, we can see that when the timer is executed, the words of not all the one thousand timers are printed at one time, but are increased by hundreds or even hundreds. Why? Another problem is involved here. If the timer time is reached, but the task in the timer is not completed, what will happen?

As we have mentioned above, when the timer time is reached, a task will be added to the JS engine thread, regardless of whether or not the statements in the task are executed completely, it will be added to the JS engine thread queue, but what about the remaining unexecuted statements?

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

Therefore, setTimeout can be defined:

Put the task into the event queue within the specified time and wait until the js engine is idle.

IV. Use of setInterval

The most basic method of setInterval is to use it directly as a cyclic timer.

SetInterval (fn, 100) is prone to a misunderstanding: the next fn execution does not start after the last fn execution is complete and then starts in MS. In fact, setInterval does not care about the last fn execution result, but puts fn into the main thread queue every MS, and the specific interval between the two fn is not necessarily long, similar to the actual latency of setTimeout, it is related to JS execution. The specific latency is related to memory and other factors.

V. Timer reliability

Although the timer tends to be stable in most cases, there are some errors in the use of the timer.

As follows:

<Script type = "text/javascript">

Var time1 = new Date (). getTime ();

SetInterval (function () {var time2 = new Date (). getTime ();

Console. log ("setInterval execution difference time:" + (time2-time1 ));

},1000 );

</Script>

The running result is as follows:

From the figure, we can basically see that there are some small errors in the timer. For example, the first running time is ms, which is 1 ms more than the set time, so we come to the conclusion: the timer is not completely reliable and has a very small error. This is the result of the test on the chrome browser. How about testing on the IE browser?

The results show that the error in IE browser is greater.

6. Wonderful use of timer

In addition to timing, the timer can also be used for time-consuming code optimization in the project:

Suppose there is a scenario where 0.5 million nodes need to be rendered on a page. In this case, direct rendering is not desirable for general projects, this will cause the browser to become stuck because it will occupy too much memory. The user mistakenly thinks that the page is stuck and directly closes the browser or kills the process, even if the user does not close the page, the user experience is poor. How can we solve this problem at this time, we can use the timer to optimize this problem. First, we can divide 0.5 million nodes into multiple groups, so there should be no more nodes in each rendering group, then, we use setInterval to loop through the JS engine thread, which neither blocks the running of the JS engine thread nor increases the rendering time consumption. To achieve final optimization rendering.

7. Timer usage precautions

If there is a timer involved in the project, remember to call the clearInterval or clearTimeout methods to clear the timer at the end of a timer, in order to avoid mutual interference between the timers, some problems may occur.

The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, you can leave a message and share your support!

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.