JavaScript asynchronous processing working mechanism detailed _javascript skill

Source: Internet
Author: User
Tags setinterval time interval

On a basic level, it is important to understand how JavaScript timers work. The execution of timers is often different from our intuitive imagination, because the JavaScript engine is single-threaded. Let's start by recognizing how the following three functions control the timer.

var id = settimeout (FN, delay); -Initializes a timer and executes after the specified interval. The function returns a unique flag ID (number type) that we can use to cancel the timer.
var id = setinterval (FN, delay); -Similar to settimeout, but it is a continuous call to a function (the interval is the delay parameter) until it is canceled.
Clearinterval (ID);, cleartimeout (ID); -Use the Timer ID (settimeout and SetInterval return values) to cancel the occurrence of the timer callback
To understand the intrinsic implementation of timers, there is an important concept to be explored: The delay of the timer (delay) is not guaranteed. Since all JavaScript code is executed in one thread, all asynchronous events (for example, mouse clicks and timers) are executed only if they have an execution opportunity.

There is a lot of information to understand in this diagram, and if you fully understand them, you will have a good idea of how the JavaScript engine implements asynchronous events. This is a one-dimensional icon: the vertical direction represents time, and the blue block represents the JavaScript code execution block. For example, the first JavaScript code execution block needs about 18MS, mouse clicks trigger the code execution block needs 11ms, and so on.

Because the JavaScript engine executes only one piece of code at a time (because of the JavaScript single-threaded nature), each JavaScript code execution block "blocks" the execution of other asynchronous events. This means that when an asynchronous event occurs (for example, when the mouse clicks, the timer is triggered, or the Ajax asynchronous request, the callback function of these events will be queued at the end of the execution queue (in fact, the queue is different depending on the browser, so here is only a simplification);

Starting with the first JavaScript execution block, two timers are initialized in the first execution block: a 10ms settimeout () and a 10ms setinterval (). Depending on when and where the timer is initialized (the timer starts after the timer is initialized), the timer is actually triggered before the first block of code is finished executing. However, a function bound by a timer is not executed immediately (because JavaScript is single-threaded) when it is not executed immediately. In fact, the deferred function is ranked at the end of the execution queue, waiting for the next appropriate time to be executed.

In addition, in the first JavaScript execution block we saw a "mouse click" event occurred. A JavaScript callback function is bound to this asynchronous event (we never know when the user will perform this (click) event, so it is considered asynchronous), this function is not executed immediately, like the timer above, it will be queued at the end of the execution queue, waiting for the next appropriate time to execute.

When the first JavaScript execution block completes, the browser immediately asks a question: which function (statement) is waiting to be executed? At this point, a "mouse click event handler" and a "timer callback function" are waiting to be executed. The browser chooses one (which actually selects the "handler function for the mouse click event", as the diagram shows it to be the advanced team) to execute immediately. The timer callback function waits for the next appropriate time to execute.

Note that when the "mouse click event handler" executes, the setinterval callback function is triggered for the first time. As with the settimeout callback function, it is queued to execute at the end of the execution queue. However, it is important to note that when the setinterval callback function is triggered the second time (at which point the settimeout function is still executing) the first trigger of setinterval will be discarded. When a long block of code executes, it is possible to put all the setinterval callback functions behind the execution queue, and after the code block executes, the result is a large string of setinterval callback functions waiting to be executed, and there is no interval between these functions until all is complete. Therefore, browsers tend to line up the next handler at the end of the queue (this is due to the interval problem) when no more interval processing functions are queued.

We can see that the previous SetInterval callback function is still executing when the third SetInterval callback function is triggered. This illustrates a very important fact: SetInterval does not consider what is currently executing, and all blocked functions are queued to the end of the queue. This means that the time interval between the two setinterval callback functions is sacrificed (scaled down).

Finally, when the second setinterval callback function completes, we can see that no program is waiting for the JavaScript engine to execute. This means that the browser is now waiting for a new asynchronous event to occur. At 50ms, a new setinterval callback function was triggered again, and no execution block blocked its execution. So it will be executed immediately.

Let's use an example to illustrate 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 lines of code look no different at first glance, but they are not. The interval between the execution of the settimeout callback function and the previous execution is at least 10ms (possibly more, but not less than 10ms), and the setinterval callback function attempts to perform every 10ms, regardless of whether the last execution was completed.

Here we have learned a lot of knowledge, summed up:

The JavaScript engine is single-threaded, forcing all asynchronous events to be queued for execution
SetTimeout and setinterval are fundamentally different when executing asynchronous code.
If a timer is blocked and cannot be executed immediately, it will delay execution until the next possible point in time (longer than expected)
If the setinterval callback function is executed long enough (longer than the specified time interval), they are executed continuously and there is no time interval between them.

The above is the entire content of this article, I hope to be able to learn JavaScript asynchronous processing help.

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.