[Javascript] How the timer in JavaScript works!

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

As a beginner, it's important to understand how a timer works in JavaScript. Often their performance behavior is not so intuitive, and this is because they are in a single thread. Let's take a look at three functions for creating and manipulating a timer.

-Initializes a single timer, and the timer will invoke the specified function after a certain delay. This function (SetTimeout) will return a unique ID that we can use to cancel the timer.

var id = setinterval (FN, delay);
-Similar to settimeout, except that it continues to invoke the specified function (each time with a delay) until the timer is canceled.

Clearinterval (ID);, cleartimeout (ID);
-Accept the ID of a timer (returned by the two functions above), and stop the timer's callback event.

To figure out how this timer works inside, there is a very important concept that needs to be raised:

1 timer delay is inaccurate (guaranteed). Because all JavaScript browser males have only one single thread to execute, and those asynchronous events (such as mouse click events, and Timers) will only be executed when the thread is idle. Here is a diagram of the demo, as follows:



There is a lot of information that needs to be understood in this diagram, but after you fully understand it, you will have a clear idea of the async mechanism in JavaScript. This diagram is one-dimensional:

In the vertical direction we mark this time in milliseconds, and this blue block represents the JavaScript code that is being executed. For example, this first executed JavaScript code took about 18 milliseconds, and the mouse event block was about 11 milliseconds, and so on.

Since the JavaScript engine will always execute only one fragment of code at the same time (because of this single-threaded mechanism), then each block of code will block (blocking) the operation of the asynchronous event.

This means that when an asynchronous event is called (for example, when a mouse click, a timer triggers a firing, or a XMLHttpRequest process is completed), it will be added to the team and deferred (as to how specifically it is entered into the queue, different browsers have different implementations, We only consider the simple case here)

From the beginning, in the first Javasript, two timers were initialized: a 10-millisecond settimeout time and a 10-millisecond setinterval event (note, here, just initialization, or definition).

Because of the time and position of the timer start, they are actually called before the first JavaScript block is completed (the call here is not executed directly, it is important to note that it is understood to be just preparing the call and adding the callback method to the queue). Note that no matter how (however), the timer does not execute immediately (because the thread has no idle reason, it cannot be executed directly). Instead, the deferred method is added to the queue and executed at a time when it can be executed (the thread is idle).

Another point, in the first JavaScript block, we can see that another mouse time has been triggered. This JavaScript callback method is associated to an asynchronous event (no one knows what time the user is doing the action, so it is considered asynchronous), and the asynchronous event is not executed immediately, and is added to the queue like the timer above.

After the first JavaScript block executes, the JavaScript engine immediately asks a question: what else is waiting for the code to be executed? So at this time, there is a mouse event callback and timer callback while waiting. The browser immediately picks a (see, mouse event callback) to execute immediately. This timer continues to wait, knowing the next possible moment.


Note that the first interval callback function is also called at the same time that the mouse event handler function is being executed. Just like the timer mentioned earlier, its callback method is added to the queue. However, note that when this interval is called again (this time the callback method of this timer is being executed), then this interval callback method will be deleted (drop). If you have many callback methods in the queue because the main thread needs to execute a block of code for a long time, then when the main thread ends, a sequence of callback functions executes without interval until the end. A good practice is to temporarily let the browser rest for a while, so that there is no interval callback in the queue.

We are seeing something: when the third interval callback method is triggered, the inteval itself is executing (this should be done next to the second interval does not end). Here is an important message to show us:

Interval does not care what the current threads are doing now, they will add their own callbacks to the queue in any case, even though it will reduce the time between two interval callback methods.

Finally, after the second interval (which should be the third one, where a drop in the middle is dropped), there is nothing in the Javasript engine to execute. This means that the browser is now waiting for a new asynchronous event to be triggered (occur). In the 50th millisecond, the Inteval callback is triggered again. At this point, there was nothing to block its execution, so it was executed immediately after it was added to the queue.

Next, let's look at an example to better understand the difference between settimeout and setinterval:

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

These two pieces of code may be very similar to the implementation of the function, casual look, they are exactly the same. In particular, this settimeout code executes the callback method at least 10 milliseconds after the last callback function executes (it may be more than 10 milliseconds, but not less than 10 milliseconds). But Setinteval will try to execute a callback function in 10 milliseconds, not to control when the last callback was executed.

These-pieces of code may appear to being functionally equivalent, at first glance, but they is not. Notably the SetTimeout code always has at least a 10ms delay after the previous callback execution (it may end ing more, but never less) whereas the setinterval would attempt to execute a callback every 10ms regardless of when the Las T callback was executed.

Here are some things we learned from here, to do a summary:

1 The JavaScript engine has only one single thread, and an asynchronous event that is being executed is added to the queue waiting.

2 settimeout and setinterval are fundamentally different from executing asynchronous callback methods.

3 If a timer that needs to be executed immediately is blocked, it cannot be deferred, knowing that the next thread is idle (the delay time will exceed the time defined by the timer)

4 interval may not delay the sequential execution of the callback method if the main thread has executed a long enough code (longer than the timed delay)


All of these are very important knowledge of how the JavaScript engine works. Especially when a large number of callback events occur, build a good foundation for us to build better application code.

----------------------------------------------------------------------------------------------------

The original is John Resig, author of jquery.

Address: http://ejohn.org/blog/how-javascript-timers-work/#postcomment



[Javascript] How the timer in JavaScript 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.