How the JavaScript timer works

Source: Internet
Author: User
Tags date count end execution functions log time in milliseconds unique id

Recently, looking at some of the JavaScript principles of the article, happened to see the jquery author of a JavaScript timer on the principle of the analysis, and so scared to decide to translate the original text into Chinese, one is to share with you, Secondly, to deepen their understanding of JavaScript. Original link: http://ejohn.org/blog/how-javascript-timers-work/

Original translation:

At the basic level, it is important to understand how the JavaScript timer works. Because JavaScript is single-threaded, many times the timer does not appear to be the same as our intuitive imagination. Let's start with the following three functions, which will give us the opportunity to construct and manipulate timers.

    • var id =settimeout (FN, delay); -Creates a simple timer that, after a given time, will be executed by the callback function. This function returns a unique ID that can be used to unregister the timer at a later time.
    • var id = setinterval (FN, delay);-similar to settimeout, but every time after a given delay, the passed function is executed once, until the timer is logged off.
    • clearInterval(id);,clearTimeout(id); -接受一个计时器ID(由之前两种计时器返回)并且停止计时器回调函数的执行。

To understand the internal workings of the timer, we first need to understand a very important concept: the timer set delay is not guaranteed. Because all JavaScript single-threaded asynchronous events performed in the browser, such as mouse click events and timers, are only performed when it is free. This is best illustrated by a picture, as shown in the following picture:

There's a lot of information in this picture that needs to be digested, but a thorough understanding of this image will give you a better idea of how JavaScript asynchronous execution works. This picture is illustrated from one dimensional point of view: in the vertical direction is the time in milliseconds, the blue block represents the

The JavaScript code snippet that is currently executing. For example, the first JavaScript executes for about 18 milliseconds, and the mouse click event takes about 11 milliseconds.

Because JavaScript can only execute a piece of code each time (based on its single-threaded attributes), all of these snippets block the execution of other asynchronous events. This means that when an asynchronous event (such as a mouse click, a timer trigger, and a XMLHttpRequest request completes) is triggered, the callback functions of these events are queued at the end of the execution queue to wait for execution (the queue is different from the browser, which is only a simplification).

Initially, in the first segment, two timers were initialized: a 10ms setTimeout and a 10ms setinterval. Because the timer is initialized where it starts, the timer is actually triggered before the first piece of code executes. However, the callback function of the timer is not executed immediately (the single-threaded limit cannot be done), instead, the callback function is placed at the end of the execution queue until the next free time to execute.

In addition, within the first block of code we saw a mouse click event happen. The JavaScript asynchronous event associated with it (we cannot predict when the user will take such an action, so this event is considered asynchronous) does not execute immediately. As with the timer, it is placed at the end of the queue to wait for execution.

As soon as the first code completes, the browser immediately asks: Who is waiting for execution? At this point, both the mouse click handler and the timer callback function are waiting to be executed. The browser selects one (the mouse-click callback function) and executes it immediately. In order to execute, the timer waits for the next possible time to execute.

We note that the first timer callback function is executed when the handler for the mouse click event is executing. As with a timer, it waits for execution behind the queue. However, we can note that the timer callback function is discarded when the timer is triggered again (at the time the timer callback function is executing). If you are executing a chunk of code, you put all the timer callback functions at the end of the queue, and the result is that a bunch of timed callback functions will be executed without interval until they are complete. Instead, the browser waits silently until more time callback functions are placed in the queue, knowing that all scheduled callback functions in the queue are executed.

In fact, we can see that when the interval callback function is executing, the interval is triggered for the third time. This gives us a very important message: interval does not care who is executing at the moment, and its callback functions enter the queue without discrimination, even if there is a possibility that the callback function will be discarded.

Finally, when the second timed callback function completes, we can see that the JavaScript engine has nothing to do with it. This means that the browser is now waiting for a new asynchronous event to occur. We can see that at 50ms, the timer callback function is triggered again. This time, however, no other code blocked his execution, so he immediately executed the timer callback function.

Let's look at an example to better illustrate setTimeout the difference with setinterval.

settimeout (function () {/
* Some long block of code ... * *
settimeout (Arguments.callee);
}, ten);
setinterval (function () {/
* Some long block of code ... */
}, 10);

At first glance the two pieces of code are functionally equivalent, but in fact they are not. It is noteworthy that setTimeout this code will require at least a delay of 10ms after each callback function execution (probably more, but not less). ButsetInterval会每隔10ms就去尝试执行一次回调函数,不管上一个回调函数是不是还在执行。

From here we can learn a lot, let us summarize:

    • The JavaScript engine has only one thread, forcing asynchronous events to join queues only to wait for execution.
    • When executing asynchronous code, setTimeout setInterval There is an essential difference.
    • If the timer is blocked by the code being executed, it will enter the tail of the queue to wait until the next possible time (possibly exceeding the set latency).
    • If the interval callback function takes a long time to execute (longer than the specified delay), interval may not delay back-to-back execution.

All of this to understand the JS engine if the work is undoubtedly very important knowledge, especially a large number of typical asynchronous events occur, to build an efficient application of code snippets is a very good basis.

Personal Opinion:

After the completion of the translation, I feel a new understanding of JavaScript asynchronous, but perhaps beginners can not understand this article, so wrote a demo, run in the NODEJS environment (browser is not easy to simulate)

var starttime = new Date (); Initialize timer var start = settimeout (function () {    var end = new Date ();     Console.log ("10ms
The timer execution completes, the distance program starts "+ (End-start) +" MS ");

}, 10); Analog mouse Click event function asyncreal (data, callback) {    Process.nexttick (function () {   
     callback ();          });
var asyncstart = new Date (); Asyncreal ("YUANZM", function () {    var asyncend = new Date ();     Console.log ("
Simulate mouse to perform event completion, spend time "+ (Asyncend-asyncstart) +" MS ");
)//Set Timer count = 1; var interval = setinterval (function () {    ++count;     if (count = = 5) {  &nbsp
;     clearinterval (interval);
   }     Console.log ("Timer event");

},10);
Simulate Phase I code execution var first = [];
var start = new Date ();
for (var i = 0;i < 10000000;i++) {    first.push (i);}var end = new Date (); Console.log ("First stage code execution complete, time" + (End-start) + "MS");

The results of the operation are as follows:

We explain this in terms of the principles in this article:

(1) The timer set at the beginning is not executed immediately after 10ms, but is added to the queue, wait until the first phase of the code execution is completed before the start of the time is not set 10ms

(2) Mouse Click event also because it is an asynchronous event, added to the queue, until the first phase of the code execution completed.

(3) Mouse Click events are added to the queue after the timer event before

(4) The last timer can be executed



Related Article

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.