Recently, I encountered some problems when writing JavaScript, that is, how the Javascript single-thread engine controls the continuous triggering of multiple JavaScript events. I found some useful materials and shared them here.
Although not originalArticleFor JavascriptProgramUseful. The translation is not very accurate, but I hope it will be useful to everyone.
John resig http://ejohn.org/blog/how-javascript-timers-work/
How JavaScript timers work
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 continuously calls a function (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 the 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. Because all JavascriptCodeIt is executed in a thread. All asynchronous events (such as mouse clicks and timers) are executed only when they have the chance of execution. Use a good chart to describe:
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 msSetTimeout ()
And a 10 msSetinterval ()
. 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 and will be executed at the next appropriate time.
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,Setinterval
The callback function is triggered for the first time. AndSetTimeout
The callback function is the same as the callback function. However, pay attention to this: WhenSetinterva
L when the callback function is triggered for the second time (at this timeSetTimeout
The function is still being executed)SetTimeout
The first trigger will be discarded. When a long code block is executedSetinterval
The callback functions are all 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 they are all completed. Therefore, browsers tendInterval
In the queue, the next processing function is placed at the end of the Team (this is due to the gap problem ).
We can find that when the thirdSetinterval
When the callback function is triggered, the previous setinterval callback function is still being executed. This illustrates a very important fact:Setinterval
All blocked functions are routed to the end of the queue without considering what is being executed. This means that the time interval between the two setinterval callback functions will be sacrificed (reduced ).
Finally, when the secondSetinterval
After the 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 newSetinterval
The callback function is triggered again. At this time, no execution block blocks its execution. So it will be executed immediately.
Let's use an example to illustrateSetTimeout
AndSetinterval
Differences:
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
AndSetinterval
There are fundamental differences in 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
Setinterval
The execution time of callback functions will be long enough (longer than the specified interval), and they will be executed continuously and there is no time interval between them.
These knowledge points are very important. Understanding how the JavaScript engine works, especially when a large number of asynchronous events (continuous) occur, can lay a solid foundation for building advanced applications.