How the JavaScript timer works

Source: Internet
Author: User
Tags time in milliseconds unique id

I've been looking at some of the JavaScript principles, and I happen to see an analysis of the author of jquery about the principle of the JavaScript timer, so I decided to translate the original into Chinese, to share with you, and secondly, to deepen your 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 JavaScript timers work. Because JavaScript is single-threaded, many times the timers do not behave as intuitively as we would have imagined. Let's start with the following three functions, which give us the opportunity to construct and manipulate timers.

    • var id =settimeout (FN, delay); -A simple timer has been created, and after a given time, the callback function will be executed. This function returns a unique ID to allow the timer to be unregistered at a later time.
    • var id = setinterval (FN, delay);-similar to settimeout, but each time (given the delay), the passed function is executed once, until the timer is written off.
    • clearInterval(id);,clearTimeout(id); -接受一个计时器ID(由之前两种计时器返回)并且停止计时器回调函数的执行。

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

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

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

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

Initially, in the first snippet, two timers were initialized: a 10ms setTimeout and a 10ms setinterval. Since the timer initializes 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 (a single-threaded limit cannot be done), instead, the callback function is queued at the end of the execution queue and waits for the next available time to execute.

In addition, within the first block of code we see a mouse click event happening. JavaScript asynchronous events associated with it (we cannot predict when the user will take such an action, so the event is considered asynchronous) and will not be executed immediately. Like a timer, it is placed at the end of the queue to wait for execution.

As soon as the first code is finished, the browser immediately issues a query: 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 chooses one (mouse-click callback function) and executes it immediately. In order to execute, the timer waits for the next possible time to execute.

We notice that the first timer callback function executes when the handler for the mouse click event is executing. As with timer timers, it is also waiting for execution behind the queue. However, we can notice that when the timer is triggered again (when the timer callback function is executing), the timer callback function is discarded. If you put all of the timer callbacks at the end of the queue when executing a chunk of code, the result is that a large set of timed callbacks will be executed with no interval until completed. Instead, the browser waits silently until more timed callback functions are placed in the queue, knowing that all the timed callback functions in the queue are executed.

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

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

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

 1  setTimeout (function   () { 2  /*   Some long block of code ...  */ 3  setTimeout (Arguments.callee, 10 4 }, 10 5  function   () { 7  /*   Some long block of code ...  */ 8 }, 

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

From here we can learn a lot, let's summarize:

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

All of these are important to understand if the JS engine is working, especially when a large number of typical asynchronous events occur, which is a very advantageous foundation for building an efficient application snippet.

Personal Insights:

After the translation is complete, the feeling for JavaScript async has a new understanding, but may not understand this article beginners, so wrote a demo, running in the NODEJS environment (browser is not easy to simulate)

1 varStartTime =NewDate ();2 3 //Initialize Timer4 varStart = SetTimeout (function() {5     varEnd =NewDate ();6Console.log (' 10ms timer execution completed, distance program start ' + (End-start) + ' MS ');7}, 10);8 9 //simulate mouse click eventsTen functionasyncreal (data, callback) { OneProcess.nexttick (function() { A callback ();  -      }); - } the varAsyncstart =NewDate (); -Asyncreal (' YUANZM ',function() { -     varAsyncend =NewDate (); -Console.log (' Simulated mouse execution event completed, Time spent ' + (Asyncend-asyncstart) + ' MS '); + }) -  + //Set Timer ACount = 1; at varInterval = SetInterval (function() { -++count; -     if(Count = = 5) { - clearinterval (interval); -     } -Console.log (' Timer event ')); in},10); -  to //simulate the first phase of code execution + varFirst = []; - varStart =NewDate (); the  for(vari = 0;i < 10000000;i++){ * First.push (i); $ }Panax Notoginseng varEnd =NewDate (); -Console.log (' First stage code execution complete, time ' + (End-start) + ' MS ');

The results of the operation are as follows:

We explain this in the light of the principle:

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

(2) The mouse Click event is also caused by an asynchronous event, which is added to the queue and then executed when the first phase of code execution is complete.

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

(4) Last timer to execute

How the JavaScript timer works

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.