[Javascript] How does a Timer (Timer) in JavaScript work !, Javascripttimer

Source: Internet
Author: User

[Javascript] How does a Timer (Timer) in JavaScript work !, Javascripttimer

As the author, it is important to understand how timer works in JavaScript. Generally, their behavior is not so intuitive, because they are all in a single thread. Let's take a look at the three functions used to create and operate timer.

var id = setTimeout(fn, delay); 

-Initialize a single timer, which will call the specified function after a certain delay. This function (setTimeout) returns a unique ID. We can use this ID to cancel timer.

var id = setInterval(fn, delay);
-It is similar to setTimeout, except that it will continuously call the specified function (each time there is a delay) until the timer is canceled.

clearInterval(id);, clearTimeout(id);
-Accept the ID of a timer (returned by the above two functions) and stop the timer callback event.

To understand how the timer works internally, a very important concept needs to be proposed:

1. The timer delay is inaccurate (guaranteed ). because only one single thread is used to execute all javascript browser male code, and those asynchronous events (such as mouse click events and timers) will only be executed when the thread is idle. A chart is shown as follows:



There is a lot of information to be understood in this figure, but after fully understanding it, you will have a clear understanding of the asynchronous mechanism in javascript. This figure is one-dimensional:

We use the unit of milliseconds to mark the time vertically. The blue square represents the javascript code being executed. For example, the first javascript code executed took about 18 ms, and the mouse event block took about 11 ms.

Because the javascript engine will always execute only one snippet of code at the same time (because of this single-threaded mechanism), then each code block will block the running of other asynchronous events.

This means that when an asynchronous event is called (for example, when a mouse clicks, a timer triggers firing, or an xmlhttprequest process is completed), it will be added to the team, and delayed execution (as for how to be added to the queue, different browsers have different implementations. Here we only consider simple cases)

From the very beginning, two timers were initialized in the first javasript: A 10-millisecond setTimeout time and a 10-millisecond setInterval event (note that only Initialization is performed here, or definition ).

Because of the start time and position of the timer, they are actually called before the completion of the first javascript block (the call here is not directly executed. Please note that, it can be understood that the callback method is only prepared to be called and added to the queue. Note that the timer will not be executed immediately regardless of the however (because the thread is not idle, it cannot be executed directly ). On the contrary, this delayed method will be added to the queue for execution at a certain time that can be executed (when the thread is idle.

In addition, in the first javascript block, we can see that another mouse time is triggered. This javascript callback method is associated with an asynchronous event (no one knows when the user will do this action, so it is considered asynchronous), and this asynchronous event will not be executed immediately, like the timer above, it will also be added to the queue.

After the execution of the first javascript block ends, the javascript engine immediately asks the following question: is there any code waiting to be executed? At this time, a mouse Event Callback and timer callback are waiting. This browser selects one (look, it is the mouse Event Callback) and runs immediately. This timer continues to wait, knowing the next possible time.


Note: When the mouse event processing function is being executed, the first interval callback function will also be called. Like the timer mentioned above, its callback method will be added to the queue. However, note that when the interval is called again (the callback method of the timer is being executed at this time), the callback method of the interval will be deleted (drop ). If the main thread needs to execute a code block for a long time, and you add many callback methods to the queue, when the main thread ends, a series of callback functions are continuously executed at no interval, until the end. It is better to temporarily let the browser wait for a while, so that there is no Interval callback in the queue.

We can see some situations: when the third interval callback method is triggered, inteval itself is being executed (Here it should be that the execution of the second interval is not completed ). An important information is shown here:

Interval does not care about what the current thread is executing. They add their callbacks to the queue in any situation, even if it reduces the time between the two interval callback methods.

Finally, after the execution of the second interval (in the figure, it should be the third, here there should be a drop in the middle), there is no other thing in the javasript engine that can be used for execution. That is to say, the browser is waiting for a new asynchronous event to be triggered (occur ). The inteval callback was triggered again in 50th milliseconds. At this time, there is nothing to block its execution, so it will be executed immediately after it is 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, 10);  }, 10);   setInterval(function(){    /* Some long block of code... */  }, 10);

These two pieces of code may be very similar in terms of function implementation. Inadvertently, they are completely the same. In particular, this setTimeout code will execute the callback method again at least 10 milliseconds after the previous callback function is executed (it may exceed 10 milliseconds, but not less than 10 milliseconds ). However, setInteval will try to execute a callback function within 10 milliseconds without worrying about the time when the previous callback was executed.

These two pieces of code may appear to be functionally equivalent, at first glance, but they are not. notably the setTimeout code will always have at least a 10 ms delay after the previous callback execution (it may end up being more, but never less) whereas the setInterval will attempt to execute a callback every 10 ms regardless of when the last callback was executed.

Here are some things we have learned from here. Let's make a conclusion:

1 The javascript engine only has one single thread, and the asynchronous events being executed will be added to the queue for waiting.

2 setTimeout and setInterval are basically different in the asynchronous callback method.

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

4 interval the callback method may be executed without delay. If the main thread executes a code long enough (longer than the scheduled delay)


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

Bytes ----------------------------------------------------------------------------------------------------

The original Article is from John Resig, the author of jQuery.

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



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.