Home  >  Article  >  Web Front-end  >  Detailed explanation of browser multi-threading mechanism

Detailed explanation of browser multi-threading mechanism

php中世界最好的语言
php中世界最好的语言Original
2018-03-16 15:20:211576browse

This time I will bring you a detailed explanation of the browser's multi-threading mechanism. What are the precautions when using the browser's multi-threading mechanism? Here are practical cases, let's take a look.

Before talking, everyone knows that js is based on a single thread, and this thread is the browser's js engine.
First, let’s take a look at the threads that everyone uses in their browsers.

If we want to perform some time-consuming operations, such as loading a large picture, we may need a progress bar to let the user wait. During the waiting process, the entire The js thread will be blocked and the subsequent code cannot run normally, which may greatly reduce the user experience. At this time, we expect to have a worker thread to handle these time-consuming operations. It was basically impossible to achieve in the traditional HTML era, but now, we have something called a worker. It is a class in js, and we only need to create an instance of it to use it.

var worker = new Worker(js file path);

ConstructionParameters of the functionFill in the path of your js file. This js file will be run in a newly opened thread of the browser and will be merged with the thread of the original js engine. No impact.

So since they do not affect each other, how do we communicate between the two threads? The answer is actually already in the code, that is, the two functions onPostMessage and onmessage, where the parameters of onPostMessage (data) are you The data to be passed, and onmessage is a callback function. Onmessage will be called back only when data is received. Onmessage has a hidden parameter, which is event. We can use event.data to get the passed The incoming data is used to update the main thread.

JavaScript's setTimeout and setInterval are two methods that can easily deceive others' feelings, because we often think that when called, it will be executed in the established way. I think many people are deeply aware of this. I feel the same way, for example

[javascript] view plain copy print?Detailed explanation of browser multi-threading mechanismDetailed explanation of browser multi-threading mechanism

  1. setTimeout( function() { alert('Hello!'); } , 0);

  2. setInterval( callbackFunction , 100);

think The greeting method in setTimeout will be executed immediately, because this is not said out of thin air, but the JavaScript API document clearly defines the meaning of the second parameter as the number of milliseconds after which the callback method will be executed. It is set to 0 milliseconds here, of course. It was executed immediately.
Similarly, I have no doubt that the callbackFunction method of setInterval is executed immediately every 100 milliseconds!

But as JavaScript application development experience continues to increase and enrich, one day you will I found a weird piece of code and couldn't figure it out:

[javascript] view plain copy print?Detailed explanation of browser multi-threading mechanismDetailed explanation of browser multi-threading mechanism

  1. p.onclick = function(){

  2. setTimeout( function(){document.getElementById('inputField').focus();}, 0);

  3. };

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:

[javascript] view plain copy print?Detailed explanation of browser multi-threading mechanismDetailed explanation of browser multi-threading mechanism

  1. setTimeout( function(){ while(true){} } , 100);

  2. ##setTimeout( function(){ alert('Hello! '); } , 200);

  3. 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 has not appeared, and there is no news from callbacKFunction!

At this time, you are completely confused. This situation is It is difficult to accept, because the process of changing long-established cognitions to accept new ideas is painful, but the facts are before our eyes, and the search for the truth of JavaScript will not stop because of pain. Let us expand the JavaScript thread and Timer exploration journey!

Open the clouds and see the moon

The main reason for all the above misunderstandings is: subconsciously believing that JavaScript engines have multiple The thread is 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 here must clarify a fact:

The JavaScript engine runs in a single thread. The browser has only one thread running the JavaScript program at any time.

The JavaScript engine uses Single-threaded operation is also meaningful. Single-threaded 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? What about?

The following is a brief explanation based on 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 certain browser The implementation of the browser kernel has at least three resident threads: JavaScript engine thread, interface rendering thread, and browser event triggering thread. 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, the following diagram illustrates how a 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 can be seen from the figure, 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 JavaScript. The code block currently executed by the engine, such as calling setTimeout to add a task, can also come from other threads in the browser kernel, such as mouse click events on interface elements, time arrival notifications, asynchronous request status change notifications, etc. .From a code perspective, task entities are various callback functions. The JavaScript engine has been waiting for 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. The corresponding small square below tn 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 time point, Let’s describe the status of other threads in the browser kernel.

t1 time:

GUI rendering thread:

This thread is responsible for rendering the browser interface

HTML element

, when the interface needs to be repainted (Repaint) or when 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 it at this time The rendering thread is mutually exclusive with the JavaScript engine thread. This is easy to understand because JavaScript scripts can manipulate DOM elements. When modifying the properties of these elements and rendering 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".

So, 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 queue until the JavaScript engine is idle. Only then will there be a chance to render it.

GUI event triggering thread:

The execution of JavaScript script does not affect the triggering of html element events. During the t1 time period, the user first clicks a mouse button. The click is captured by the browser event triggering thread and forms a mouse click event. As can be seen from the figure, for For the JavaScript engine thread, this event is asynchronously transmitted to the end of the task queue by other threads. Since the engine is processing the task at t1, 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 is single-threaded. If it is in a blocked thread state, it cannot count the time. It must rely on the outside to time and trigger the timing, so the queue The timing event is also an asynchronous event.

As can be seen from the figure, in this t1 time period, after the mouse click event is triggered, the previously set setTimeout timing has also arrived. At this moment, for the JavaScript engine, the timing The triggering thread generates an asynchronous timed event and puts it in the task queue. The event is queued after the click event callback and waits for processing.
Similarly, still within the t1 time period, a setInterval timer is also called next. Added, because it is interval timing, it is triggered twice in succession within the t1 period, and these two events are queued to the end of the queue to wait for processing.

It can be seen that if the time period t1 is very long, much larger than setInterval Timing interval, 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. However, once t1 and the tasks before the first timing event have been processed, the tasks in these arrangements will Timing events are executed in sequence without interruption. This is because, for the JavaScript engine, each task in the processing queue is processed in the same way, but in a different order.

After t1, That is to say, the currently processed task has been returned. The JavaScript engine will check the task queue and find that the current queue is not empty. Then it will take out the corresponding task under t2 and execute it, 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. Other tasks in the queue cannot be executed before the task returns. .

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

[javascript] view plain copy print?Detailed explanation of browser multi-threading mechanismDetailed explanation of browser multi-threading mechanism

  1. setTimeout(function(){

  2. /* Code block... */

  3. setTimeout(arguments.callee, 10);

  4. }, 10);


  5. ##setInterval(function(){

  6. /*Code block... */

  7. }, 10);

This The two pieces of code seem to have the same effect together, but in fact they are not. The setTimeout in the callback function in the first piece is to set a new setTimeout timing after the JavaScript engine is executed. Assume that there is a time interval from the completion of the previous callback to the start of the next callback. Theoretically, the execution time interval between two setTimeout callbacks >= 10ms. In the second section, after the setInterval sets the timing, the timing trigger thread will continue to fire every ten seconds. Seconds generate an asynchronous timed event and put it at the end of the task queue. Theoretically, the execution time interval between two setInterval callbacks is

Case 2: Is the Ajax asynchronous request 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, but this request is newly opened by the browser. A thread request (see the figure above), when the requested status 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 the task is processed, the JavaScript engine will always It is a single-thread running callback function. Specifically, it is a function set by single-thread running onreadystatechange.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

The use of single-threaded JS and multi-threaded browsers

Some minor issues about type conversion in js

Display type conversion in JS

How to implement horizontal scrolling and floating navigation in js

The above is the detailed content of Detailed explanation of browser multi-threading mechanism. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn