Can JavaScript be multithreaded? In-depth understanding of javascript timing mechanisms

Source: Internet
Author: User

JavaScript's settimeout and setinterval are two very easy ways to deceive others, because we start to think that the call will be executed in a given way, and I think a lot of people have the same feeling. For example, copy code code as follows:
SetTimeout (function () {alert (' Hello! ');}, 0);
SetInterval (callbackfunction, 100);
It is thought that the greeting method in settimeout will be executed immediately, because it is not a thin air, but rather the JavaScript API document explicitly defines how many milliseconds the second parameter is meant to be, and the callback method is executed. This is set to 0 milliseconds, which is taken for granted immediately.
In the same way, the Callbackfunction method of setinterval is executed every 100 milliseconds at once.

But as JavaScript application development experience continues to grow and enrich, one day you find a strange piece of code and think about it: Copy the Code code as follows:
Div.onclick = function () {
SetTimeout (function () {document.getelementbyidx_x_x (' Inputfield '). focus ();}, 0);
};
Since it is executed in 0 milliseconds, then what is still done with settimeout, at this moment, the firm faith has begun to waver.

Until the end of the day, you accidentally wrote a bad code: Copy the Code code as follows:
SetTimeout (function () {while (true) {}}, 100);
SetTimeout (function () {alert (' Hello! ');}, 200);
SetInterval (callbackfunction, 200);
The first line of code goes into the dead loop, but soon you'll find that the second, the third line is not the expected thing, the alert greeting does not appear, Callbackfunction also heard!

It's hard to accept that you're completely lost, because it's painful to change the long-established perception of the process of accepting new ideas, but the truth is that the quest for JavaScript truth doesn't stop because of pain, Let's expand the JavaScript thread and timer Discovery tour!

Remove the clouds and see the Moon Ming

One of the main reasons for all of the above myths is that the JavaScript engine has multiple threads executing, and the JavaScript timer callback function executes asynchronously.

In fact, JavaScript uses a decoy, and in most cases it deceives our eyes, where the backlight clarifies the fact that:

JavaScript engines are single-threaded, and browsers run JavaScript programs at all times and only one thread.

It makes sense to use a single-threaded JavaScript engine, and a single thread does not have to worry about threads synchronizing these complex problems, which are simplified.

So how does a single-threaded JavaScript engine work with the browser kernel to handle these timers and respond to browser events?
The following is a simple description of the browser kernel processing method.

The browser kernel implementation allows multiple threads to execute asynchronously, and these threads mate with each other in the kernel to maintain synchronization. If the implementation of a browser kernel has at least three resident threads: JavaScript engine thread, interface rendering thread, browser event trigger thread, and some other threads that are terminated after execution , such as HTTP request threads, which produce different asynchronous events, the following diagram illustrates how the single-threaded JavaScript engine interacts with other threads. Although each browser core implementation is different in detail, the invocation principle is similar.


As can be seen from the diagram, the JavaScript engine in the browser is event-driven, where events can be seen as a variety of tasks that the browser assigns to it, which can originate from the code blocks that the JavaScript engine is currently executing, such as calling settimeout to add a task, It can also be from other threads of the browser kernel, such as interface element mouse Click event, timing trigger time arrival notification, asynchronous request status change notification, etc. from a code perspective, the task entity is a variety of callback functions, and the JavaScript engine waits for tasks in the task queue to arrive. Because of single-threaded relationships, These tasks have to be queued, one after the other by the engine.

T1-t2. TN represents a different point in time, and the corresponding small square below the TN represents the task at that point in time, assuming the T1 moment, the engine runs in the T1 corresponding task block code, and at this point in time, we describe the state of the other threads in the browser kernel.

T1 moment:

GUI Render Thread:

The thread is responsible for rendering the browser interface HTML element, which executes when the interface needs to be redrawn (Repaint) or when a return (reflow) occurs because of an operation. This paper focuses on the JavaScript timing mechanism, but it is necessary to say the rendering thread, Because this thread is mutually exclusive to the JavaScript engine thread, it is easy to understand that because JavaScript scripts are manipulated DOM elements and render the interface while modifying these element properties, the element data obtained before and after the render thread may be inconsistent.

During the scripting run by the JavaScript engine, the browser render thread is in a suspended state, which means it is "frozen".

As a result, updates to the interface, such as adding nodes, deleting nodes, or changing the appearance of nodes, are not immediately reflected in the script, which is saved in a queue and is only available for rendering when the JavaScript engine is idle.

GUI Event Trigger Thread:

The execution of JavaScript scripts does not affect the triggering of HTML element events, in the T1 time period, the first is the user clicked a mouse button, click the browser event triggered by the thread capture after a mouse click event, by the figure, for the JavaScript engine thread said, This event is transmitted asynchronously to the end of the task queue by another thread, and the mouse click event is waiting to be processed because the engine is working on the T1 task.

Timed Trigger Thread:

Note that the browser model timer counters here are not counted by the JavaScript engine, because the JavaScript engine is single-threaded and if it is not counted when it is in a blocked thread state, it must rely on the outside to timing and trigger the timing, so the timed events in the queue are also asynchronous events.

From the figure, in this T1 time period, after the mouse click event triggered, the previously set of settimeout timed also arrived, at the moment for the JavaScript engine, the timed trigger thread produced an asynchronous timed event and placed in the task queue, the event is queued to the Click event Callback, Wait for processing.
In the same vein, or in the T1 time period, the next setinterval timer was added, due to the interval timing, in the T1 segment is triggered two times, the two events are queued to the end of the queue for processing.

As can be seen, if the time period T1 very long, much larger than the timing interval of setinterval, then the timed trigger thread will continuously generate asynchronous timed events and put to the end of the task queue, regardless of whether they have been processed, but once the T1 and the first scheduled event before the task has been processed, The timed events in these permutations are executed sequentially, because, for the JavaScript engine, each task in the processing queue is handled the same way, only in a different order.

After T1, that is, the currently processed task is returned, the JavaScript engine checks the task queue, finds that the current queue is non-empty, takes out the corresponding task execution under T2, and so on, and so on, it looks like this:

If the queue is not empty, the engine takes a task out of the queue header until the task finishes processing, returning the engine to run the next task, and other tasks in the queue that are not returned by the task cannot be executed.

I believe you are now well aware that JavaScript is multi-threaded and understand how JavaScript timer works, let's take a look at some of these cases:

Case 1:settimeout and setinterval copy the code code as follows:
SetTimeout (function () {

SetTimeout (Arguments.callee, 10);
}, 10);

SetInterval (function () {

}, 10);
These two pieces of code see the same effect, in fact, the first paragraph in the callback function settimeout is the JavaScript engine to set a new settimeout timing, assuming that the last callback processing until the next callback to start processing as a time interval, Theory two settimeout callback execution interval >=10ms. The second paragraph since the setinterval set timing, timed trigger thread will continue to generate asynchronous timed events every 10 seconds and put to the end of the task queue, theoretically two setinterval Callback execution Interval <=10.

Case 2:ajax is the asynchronous request really asynchronous?

Many classmates friends do not know, since said JavaScript is single-threaded run, then XMLHttpRequest after the connection is really asynchronous?
The request is actually asynchronous, but the request is made by the browser to open a new thread request (see), when the state of the request changes, if the callback was previously set, this asynchronous thread will produce a state change event in the JavaScript engine processing queue to wait for processing, when the task is processed, The JavaScript engine is always a single-threaded run callback function, or a single-threaded run of the function set by onreadystatechange.

Can JavaScript be multithreaded? In-depth understanding of javascript timing mechanisms

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.