Can JavaScript be multithreaded?

Source: Internet
Author: User
Tags http request setinterval time interval

The settimeout and setinterval of JavaScript are two easy ways to cheat people's feelings, because we start to think that the call will be executed in a way that I think a lot of people are feeling, like [JavaScript]

settimeout (function () {alert (' Hello! ');}, 0;

SetInterval (callbackfunction, 100);

settimeout (function () {alert (' Hello! ');}, 0;

SetInterval (callbackfunction, 100);

It is assumed that the greeting method in settimeout is executed immediately, because it is not a figment of the imagination, but rather a JavaScript API document that explicitly defines how many milliseconds the second parameter meaning is, and the callback method is executed. This is set to 0 milliseconds, and is taken for granted immediately.

The same callbackfunction method for SetInterval is executed immediately at intervals of 100 milliseconds. Believe it!

But with the growing and enriching experience of JavaScript application development, one day you find a strange piece of code that you don't understand:

[JavaScript]

Div.onclick = function () {

settimeout (function () {document.getElementById (' Inputfield '). focus ();}, 0);

};

Div.onclick = function () {

settimeout (function () {document.getElementById (' Inputfield '). focus ();}, 0);

};

Since it is 0 milliseconds to execute, then what else to do with settimeout, at the moment, the firm belief has begun to waver.

Until the very last day, you accidentally wrote a bad piece of code:

[JavaScript]

settimeout (function () {while (true) {}}, 100);

settimeout (function () {alert (' Hello! ');}, 200;

SetInterval (callbackfunction, 200);

settimeout (function () {while (true) {}}, 100);

settimeout (function () {alert (' Hello! ');}, 200;

SetInterval (callbackfunction, 200);

The first line of code into the dead loop, but soon you will find that, second, the third line is not expected, alert greetings have not seen, Callbackfunction also heard!

When you are completely lost, this scenario is difficult to accept, because the process of changing a long established awareness to accept new ideas is painful, but the reality is that the search for JavaScript truth does not stop with pain, Let's start with the JavaScript thread and the Timer Discovery tour!

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

As a matter of fact, JavaScript uses a decoy that, in most cases, deceives our eyes, and here the backlight clarifies a fact:

JavaScript engines are single-threaded, and browsers run JavaScript programs whenever and only one thread.

The JavaScript engine is also meaningful to run single-threaded, and the problem is simplified by a single thread that ignores the complex issues of threading synchronization.

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 how the browser kernel is handled.

The browser kernel implementation allows multiple threads to execute asynchronously, these threads work with each other in a kernel system to keep the synchronization. If the implementation of a browser kernel has at least three permanent threads: JavaScript engine thread, interface rendering thread, browser event triggering thread, in addition to some, there are some threads that terminate at the end of execution , such as HTTP request threads, which produce different asynchronous events, the following diagram illustrates how the single-threaded JavaScript engine interacts with the other threads. Although each browser kernel implements different details, the invocation principle is similar.

The settimeout and setinterval of JavaScript are two easy ways to cheat people's feelings, because we start to think that the call will be executed in a way that I think a lot of people would agree with, such as

As can be seen from the diagram, the JavaScript engine in the browser is event-based, and the event can be seen as a variety of tasks that the browser sends to it, from the code blocks currently executing by the JavaScript engine, such as invoking settimeout to add a task. Can also come from the browser kernel of other threads, such as interface element mouse Click event, timing trigger time arrival notification, asynchronous request status change notification, etc. from the point of view of the code, the task entity is a variety of callback functions, and the JavaScript engine waits for the task queue to arrive. Because of the single-threaded relationship, These tasks have to be queued, one after the other, and the engine is processed. Above Figure t1-t2 ... TN represents a different point in time, TN the corresponding small squares represent the task at that point in time, assuming now is the T1 moment, the engine runs in the T1 corresponding task square code, at this point in time, we describe the state of the browser kernel other threads.

T1 moment:

GUI Render Thread:

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

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

Therefore, updates to the interface in a script, such as adding a node, deleting a node, or changing the appearance of a node, are not immediately apparent, and these actions are saved in a queue and are not rendered until the JavaScript engine is idle.

GUI Event Trigger Thread:

JavaScript script execution does not affect the triggering of HTML element events, in the T1 time period, the first is the user clicked on a mouse button, click on the browser event triggered by the thread capture after the formation of a mouse click event, from the figure that, for JavaScript engine thread said, This event is passed asynchronously to the end of the task queue by other threads, and the mouse-click event is waiting to be processed because the engine is processing the T1 task.

Timed Trigger Thread:

Note that the browser Model timer counter here is not counted by the JavaScript engine because the JavaScript engine is single-threaded and, if it cannot be counted in a blocked thread state, it must rely on external timing and trigger timing, so the timed event in the queue is also an asynchronous event.

From the figure, in this T1 time period, after the mouse click event triggered, the previous set of SetTimeout timed also arrived, now for the JavaScript engine, the timing trigger thread produced an asynchronous timed event and placed in the task queue, the event was queued to the Click event Callback, Waiting to be processed.

Similarly, in the T1 time period, the next setinterval timer was added, due to the interval timing, in the T1 segment was triggered two consecutive times, the two events were queued to the end of the queue to be processed.

Visible, if the time period T1 is very long, much larger than the setinterval interval, then the timer trigger thread will continuously produce 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 JavaScript engines, the tasks in the processing queue are handled the same way, but the order of processing is different.

After T1, which means that the currently processed task is returned, the JavaScript engine checks the task queue, finds that the current queue is not empty, takes out the corresponding task execution under T2, and so on, and so on, which appears to be:

If the queue is not empty, the engine pulls a task from the queue header until the task is processed, returning the engine to the next task, and the other tasks in the queue before the task is returned cannot be performed.

I believe you are now well aware that JavaScript is multi-threaded and understand how the JavaScript timer works, and we'll look at some of these cases:

Case 1:settimeout and SetInterval

[JavaScript]

settimeout (function () {

/* code block ... * *

SetTimeout (Arguments.callee, 10);

}, 10);

SetInterval (function () {

/* code block ... * *

}, 10);

settimeout (function () {

/* code block ... * *

SetTimeout (Arguments.callee, 10);

}, 10);

SetInterval (function () {

/* code block ... * *

}, 10);

The two pieces of code look like the same effect, in fact, the first paragraph in the callback function settimeout is the JavaScript engine after the execution of a new settimeout timing, assuming that the previous callback is processed to the next callback to start processing as a time interval, Theory two settimeout callback execution interval >=10ms. After the second paragraph from the setinterval set timer, the timer trigger thread will continuously generate asynchronous timed events every 10 seconds and put the end of the task queue, theoretically two setinterval callback execution Interval between <=10.

Case 2:ajax is the asynchronous request really asynchronous?

Many classmates and friends do not know, since that JavaScript is single-threaded run, then XMLHttpRequest after the connection is really asynchronous?

The request is actually asynchronous, however, this request is a new thread request from the browser (see above), and when the requested state changes, if the callback was previously set, the asynchronous thread is placed in the processing queue of the JavaScript engine to wait for processing when the task is processed. The JavaScript engine is always single-threaded to run the callback function, which is the function set by the single-threaded run onreadystatechange.

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.