How the timer in JavaScript JavaScript works (Settimeout,setinterval)

Source: Internet
Author: User
Tags setinterval unique id

Original (http://www.yeeyan.org/articles/view/luosheng/24380)

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.

    • var id = setTimeout(fn, delay);-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); -accepts the ID of a timer (returned by the two functions above), and stops the timer's callback event.

To understand how the timer works internally, we also need to know a very important concept: the timer's delay is not always what you want it to be. Because all JavaScript in the same browser executes only on a single thread, those asynchronous events (such as a mouse click, or a timer) run only when the execution period is idle. This diagram is the best to be clear, see:


(Click to view larger image)

There is a lot of information that can be mined in this example, but you will have a clearer idea of how asynchronous JavaScript executes after you fully understand it. This is a one-dimensional figure: in the vertical direction is the (wall clock) time, in milliseconds. A blue box indicates the JavaScript fragment that is being executed. For example, the first JavaScript executes about 18ms, while the mouse click executes about 11ms, and so on.

Since JavaScript has always been able to execute a piece of code at the same time (which is determined by the nature of its single thread), each block of code "blocks" other asynchronous events. This means that when an asynchronous event occurs (such as a mouse click, a timer trigger, or a xmlhttprequest complete), these events go into a queue to wait for execution (the implementation method of the queue will vary by browser, and we will only discuss a simplified scenario here).

Initially, in the first JavaScript block, two timer was initialized: a 10ms settimeout and a 10ms setinterval. Since the timer (the timer here refers to the timer in settimeout, and the interval in the following refers to the timer in setinvertal), it is actually triggered before the end of the first block of code. Note, however, that it does not execute immediately (in fact, it cannot be executed immediately because of the existence of a single thread). Instead, the deferred function enters the queue and waits for it to be executed when it is idle.

In addition, in the first JavaScript block, we see a mouse click event also occurred. And with this asynchronous event (we don't know when the user is going to perform an action, so the JavaScript callback function that it thinks is an asynchronous action) is not executed immediately, just like a timer, and it goes into the queue waiting to be executed.

When the first JavaScript block is executed, the browser asks a question: Is there code waiting to be executed? In this example, both mouse click events and time events are waiting in the queue. The browser then chose one (mouse click event) and then executed it immediately. And the timer can only continue to wait.

Note that the first interval event is triggered when the mouse click event is executing, and as with a timer, its events are queued for execution. However, note that when the interval is triggered again (this time the timer event is executing), this time its event is discarded. If you hoard all the interval callback functions when a large JavaScript block is executing, the result is that a bunch of interval events will be executed after the JavaScript blocks have been executed, and there will be no gaps in the execution process. Instead, the browser prefers to wait to ensure that there are no other interval in the queue when a interval enters the queue.

In fact, we can see in the example that the interval itself is executing when the third interval is triggered. This tells us an important fact: interval is whatever it is currently doing, and in any case it will go into the queue, even if it means that the time between each callback is inaccurate.

Finally, when the second interval callback is executed, we can see that the queue has been emptied and there is nothing to do with the JavaScript engine. This indicates that the browser is now waiting for a new asynchronous event to occur. So at 50ms we saw that interval was triggered again. This is the same, because nothing is blocking its execution, it immediately triggers.

Let's look at an example that illustrates the difference between settimeout and setinveral better.

SetTimeout (function () {
/* A very long code block ... * *
SetTimeout (Arguments.callee, 10);
}, 10);

SetInterval (function () {
/* A very long code block ... * *
}, 10);

At first glance, the two pieces of code appear to be functionally identical, but in fact this is not the case. SetTimeout's code will always have at least 10ms latency after the previous callback has been executed (more likely, but never less), while SetInterval always tries to execute a callback every 10ms, regardless of when the last callback was executed.

We've learned a lot here, so let's recap:

    • The JavaScript engine has only one thread, which causes asynchronous events to be queued for execution.
    • setTimeout和setInterval在如何执行代码上有着本质地区别。
    • If a timer is blocked when it is going to be executed, it will wait for the next time (longer than expected).
    • If the interval takes longer to execute (longer than the specified delay), then they will be executed continuously without delay.

The above knowledge is of considerable importance. Knowing how the JavaScript engine works, especially knowing how it works when there are many asynchronous events, lays a solid foundation for us to write advanced application code.

How the timer in JavaScript JavaScript works (Settimeout,setinterval)

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.