For example,
setTimeout( function(){ alert('Hello !'); } , 0);
setInterval( callbackFunction , 100);
It is believed that the greeting method in setTimeout will be executed immediately, because this is not said out of thin air, but JavaScript The API document clearly defines the meaning of the second parameter as the number of milliseconds after which the callback method will be executed. If it is set to 0 milliseconds, of course it will be executed immediately.
Similarly, the callbackFunction method of setInterval will be executed every 100 milliseconds. You have no doubt that it will be executed immediately!
But as your JavaScript application development experience continues to increase and enrich, one day you find a strange piece of code and you are puzzled:
div.onclick = function(){
setTimeout( function(){document.getElementById ('inputField').focus();}, 0);
};
Since it is executed after 0 milliseconds, why use setTimeout? At this moment, the firm belief has begun to waver. .
Until the last day, you accidentally wrote a piece of bad code:
setTimeout( function(){ while(true){} } , 100);
setTimeout( function(){ alert('Hello!'); } , 200);
setInterval( callbackFunction , 200);
The first line of code enters an infinite loop, but soon you will find that the second and third lines are not what you expected, the alert greeting does not appear, and there is no news from the callbacKFunction!
At this time, you are completely confused. This situation is difficult to accept, because the process of changing the long-established cognition to accept new ideas is painful, but the facts are before you, and the search for the truth of JavaScript will not be because of pain. And stop, let us start the journey of exploring JavaScript threads and timers!
Open the clouds and see the moonlight
The main reason for all the above misunderstandings is: subconsciously believing that, The JavaScript engine has multiple threads executing, and the timer callback function of JavaScript is executed asynchronously.
In fact, JavaScript uses a blinding method to deceive our eyes most of the time. The backlight needs to be clarified here. A fact:
The JavaScript engine runs in a single thread, and the browser has only one thread running the JavaScript program at any time.
It also makes sense for the JavaScript engine to run in a single thread. , a single thread does not have to worry about complex issues such as thread synchronization, and the problem is simplified.
So how does the single-threaded JavaScript engine cooperate with the browser kernel to process these timers and respond to browser events?
The following A brief explanation combined with the browser kernel processing method.
The browser kernel implementation allows multiple threads to execute asynchronously. These threads cooperate with each other under kernel control to maintain synchronization. If a browser kernel has at least three implementations Resident threads: JavaScript engine threads, interface rendering threads, browser event triggering threads. In addition to these, there are also some threads that terminate after execution, such as HTTP request threads. These asynchronous threads will generate different asynchronous events. Here is a picture To illustrate how the single-threaded JavaScript engine interacts and communicates with other threads. Although the implementation details of each browser kernel are different, the calling principles are similar.
As you can see from the picture It turns out that the JavaScript engine in the browser is event-driven. The events here can be regarded as various tasks assigned to it by the browser. These tasks can originate from the code block currently executed by the JavaScript engine, such as calling setTimeout to add a task. , can also come from other threads in the browser kernel, such as interface element mouse click events, scheduled trigger time arrival notifications, asynchronous request status change notifications, etc. From a code perspective, task entities are various callback functions, and the JavaScript engine has been waiting The arrival of tasks in the task queue. Due to the single-thread relationship, these tasks have to be queued and processed by the engine one after another.
The above figure t1-t2..tn represents different time points, and the corresponding small ones below tn The box represents the task at that time point. Assume that it is time t1 and the engine is running in the task block code corresponding to t1. At this point in time, let us describe the status of other threads in the browser kernel.
t1 Time:
GUI rendering thread:
This thread is responsible for rendering the HTML elements of the browser interface. When the interface needs to be redrawn (Repaint) or a reflow is caused by some operation, this thread will be executed. Although this article focuses on explaining the JavaScript timing mechanism, it is necessary to talk about the rendering thread at this time, because this thread and the JavaScript engine thread are mutually exclusive. This is easy to understand, because JavaScript scripts can manipulate DOM elements. When modifying these If the element attributes render the interface at the same time, the element data obtained before and after the rendering thread may be inconsistent.
While the JavaScript engine is running the script, the browser rendering thread is in a suspended state, which means it is "frozen" ”.
Therefore, updates to the interface performed in the script, such as adding nodes, deleting nodes, or changing the appearance of nodes, will not be reflected immediately. These operations will be saved in a In the queue, the JavaScript engine will have the opportunity to render when it is idle.
GUI event triggering thread:
The execution of JavaScript scripts does not affect the triggering of html element events. During the t1 time period, first The user clicks a mouse button. The click is captured by the browser event trigger thread and forms a mouse click event. As can be seen from the figure, for the JavaScript engine thread, this event is asynchronously transmitted to the end of the task queue by other threads. Since the engine The task at t1 is being processed, and this mouse click event is waiting to be processed.
Timing trigger thread:
Note that the browser model timing counter here is not counted by the JavaScript engine, because the JavaScript engine It is single-threaded. If it is in the blocked thread state, it cannot count the time. It must rely on the outside to time and trigger the timing, so the timing events in the queue are also asynchronous events.
As can be seen from the picture, at the time of t1 Within the segment, after the mouse click event is triggered, the previously set setTimeout timing has also arrived. At this moment, for the JavaScript engine, the timing trigger thread generates an asynchronous timing event and puts it in the task queue. The event is queued to the click event. After the callback, wait for processing.
Similarly, still in the t1 period, a setInterval timer is also added next. Because it is interval timing, it is triggered twice in a row in the t1 period. These two The event is queued to the end of the queue to be processed.
It can be seen that if the time period t1 is very long, much larger than the timing interval of setInterval, then the timing trigger thread will continuously generate asynchronous timing events and put them at the end of the task queue regardless of whether they have been processed, but once t1 and the first After the tasks in front of the scheduled event have been processed, the scheduled events in these arrangements will be executed one after another without interruption. This is because, for the JavaScript engine, each task in the processing queue is processed in the same way. The order is just different.
After t1, that is to say, the currently processed task has been returned, the JavaScript engine will check the task queue, and if it finds that the current queue is not empty, it will take out the corresponding task under t2 for execution, and so on at other times. , from this point of view:
If the queue is not empty, the engine will take out a task from the head of the queue until the task is processed, that is, after returning, the engine will then run the next task. Before the task returns, the engine will Other tasks cannot be executed.
I believe you now have a clear understanding of whether JavaScript can be multi-threaded, and also understand the JavaScript timer operating mechanism. Let’s analyze some cases:
Case 1: setTimeout and setInterval
setTimeout(function( ){
/* Code block... */
setTimeout(arguments.callee, 10);
}, 10);
setInterval(function(){
/ *Code block... */
}, 10);
These two pieces of code look the same together, but they are not. The setTimeout in the callback function in the first paragraph is the JavaScript engine. After execution, set a new setTimeout timing. Assume that there is a time interval from the completion of the previous callback processing to the start of the next callback processing. Theoretically, the execution time interval of two setTimeout callbacks >= 10ms. The second period is triggered regularly after the setInterval is set. The thread will continuously generate asynchronous timing events every ten seconds and put them at the end of the task queue. Theoretically, the execution time interval between two setInterval callbacks is
Case 2: ajax asynchronous request Is it really asynchronous? Many classmates and friends are confused. Since JavaScript is said to run in a single thread, is XMLHttpRequest really asynchronous after connecting?
In fact, the request is indeed asynchronous. However, this request is made by the browser to open a new thread (see the picture above). When the status of the request changes, if a callback has been set previously, the asynchronous thread will generate a status change event and put it in the JavaScript engine's processing queue to wait for processing. When a task is processed, the JavaScript engine always runs the callback function in a single thread, specifically the function set by onreadystatechange in a single thread.