Detailed description of javascript asynchronous processing mechanism, javascript asynchronous Processing

Source: Internet
Author: User

Detailed description of javascript asynchronous processing mechanism, javascript asynchronous Processing

At the basic level, it is very important to understand how the JavaScript timer works. Timer execution is often different from our intuitive imagination, because the JavaScript engine is single-threaded. Let's first understand how the three functions under the timer control the timer.

Var id = setTimeout (fn, delay);-initialize a timer and run it after the specified interval. This function returns a unique identifier ID (Number type), which can be used to cancel the timer.
Var id = setInterval (fn, delay);-it is similar to setTimeout, but it calls a function continuously (the interval is the delay parameter) until it is canceled.
ClearInterval (id);, clearTimeout (id);-use the timer ID (returned values of setTimeout and setInterval) to cancel the occurrence of timer callback.
To understand the internal execution principle of a timer, there is an important concept that needs to be discussed: the timer delay (delay) cannot be guaranteed. Since all JavaScript code is executed in one thread, all asynchronous events (such as mouse clicks and timers) are executed only when they have execution opportunities.

There is a lot of information to understand in this chart. If you fully understand them, you will have a good understanding of how the JavaScript engine implements asynchronous events. This is a one-dimensional icon: the vertical direction indicates the time, and the blue block indicates the JavaScript code execution block. For example, the first JavaScript code execution block takes about 18 ms, and the code execution block triggered by clicking the mouse takes 11 ms.

Because the JavaScript engine only executes one piece of code at a time (this is due to the nature of a single JavaScript thread), every JavaScript code execution block will "Block" the execution of other asynchronous events. This means that when an asynchronous event occurs (for example, a mouse click, a timer is triggered, or an Ajax asynchronous request, the callback functions of these events will be placed at the end of the execution Queue (in fact, the queuing method varies with the browser, so this is just a simplified process );

Starting from the first JavaScript execution block, two timers are initialized in the first execution block: A 10 ms setTimeout () and a 10 ms setInterval (). The timer is triggered before the execution of the first code block, depending on when and where the timer is initialized (the timer starts timing after initialization. However, the function bound to the timer will not be executed immediately (the reason for not being executed immediately is that JavaScript is single-threaded ). In fact, the delayed functions will be placed at the end of the execution queue in sequence, waiting for the next appropriate time for execution.

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

After the first JavaScript execution block is executed, the browser immediately asks the following question: which function (statement) is waiting to be executed? At this time, a "mouse click event processing function" and a "timer callback function" are waiting for execution. The browser selects a (actually selects the "processing function of the mouse click event", because the figure shows that it is the first team) to execute immediately. The "timer callback function" will wait for the next appropriate time for execution.

Note: When the "mouse click event processing function" is executed, the setInterval callback function is triggered for the first time. Like the callback function of setTimeout, It is scheduled to wait for execution at the end of the execution queue. However, pay attention to this: when the setInterval callback function is triggered for the second time (the setTimeout function is still being executed), the first trigger of setInterval will be discarded. When a long code block is executed, all the setInterval callback functions may be placed behind the execution queue. After the code block is executed, the result is a large string of setInterval callback functions waiting for execution, and there is no interval between these functions until all of them are completed. Therefore, the browser tends to route the next processing function to the end of the queue when there are no more interval processing functions (this is due to the gap problem ).

We can find that when the third setInterval callback function is triggered, the previous setInterval callback function is still being executed. This illustrates a very important fact: setInterval does not consider what is currently being executed, but routes all blocked functions to the end of the queue. This means that the time interval between the two setInterval callback functions will be sacrificed (reduced ).

Finally, after the second setInterval callback function is executed, we can see that no program is waiting for the JavaScript engine to execute. This means that the browser is waiting for a new asynchronous event. At 50 ms, a new setInterval callback function is triggered again. At this time, no execution block blocks the 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, 10 );   }, 10 );    setInterval ( function ( ) {    /* Some long block of code... */   }, 10 ); 

At first glance, there is no difference between the two sentences, but they are different. The interval between the execution of the setTimeout callback function and the last execution is at least 10 ms (more, but not less than 10 ms ), the callback function of setInterval will try to run every 10 ms, regardless of whether or not the last execution is complete.

Here we have learned a lot of knowledge, to sum up:

The JavaScript engine is single-threaded and forces 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 be executed until the next possible execution time point (longer than the expected interval)
If the execution time of the setInterval callback function is long enough (longer than the specified interval), they will be executed continuously and there is no time interval between them.

The above is all the content of this article, hoping to help you learn javascript asynchronous processing.

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.