Single-threaded asynchronous synchronous blocking non-blocking

Source: Internet
Author: User

JavaScript is a single-threaded in-depth analysis

First of all: Why is JavaScript single-threaded but it allows Ajax to be sent and callback requests, and SetTimeout also look like multi-threaded?

First Look at example 1:

1 function foo () {2     console.log (' first ' ); 3     function () {Console.log (' second ');}), 5); 4 }5 for (var i = 0; i < 1000000; i++) {6     Foo (); 7 }

Execution results are as follows

Show 10,000 first first, then show 10,000 second

JavaScript is single-threaded

Because JS runs in the browser, is single-threaded , each window a JS thread, since it is single-threaded, at a certain time only the specific code can be executed, and block other code.

While the browser is event-driven, many of the driven in the browser are asynchronous (asynchronized), creating events and putting them into the execution queue. The JavaScript engine is a single-threaded task queue, which you can understand as a queue of normal functions and callback functions. When an asynchronous event occurs, such as mouse click, a timer firing, or an XMLHttpRequest completing (mouse click event occurrence, Timer trigger event, XMLHttpRequest completion callback trigger, etc.), they put in the execution queue and wait for the current code to finish executing.

Asynchronous event-driven

As mentioned earlier, the browser is event driven, and many behaviors in the browser are asynchronous (asynchronized), such as: Mouse click event, window Size drag event, Timer trigger event, XMLHttpRequest completion callback and so on.

When an asynchronous event occurs , it enters the event queue.

The browser has an internal large message loop , event loop, which polls the large event queue and handles events. For example, the browser is currently busy processing the OnClick event when another event occurs (such as window OnSize), and the asynchronous event is placed in the event queue for processing, and only the previous processing is complete. It is idle to execute the event. SetTimeout is the same, when the call, the JS engine will start timer timers, about XXMS after the execution of XXX, when the timer time, the event is placed in the main event queue waiting for processing ( the browser is not busy when the real implementation ).

The browser is not a single thread

Although JS runs in the browser, is single-threaded, each window a JS thread, but the browser is not single-threaded , such as WebKit or Gecko engine, may have the following thread:

    • JavaScript engine thread
    • Interface Rendering Thread
    • Browser Event Trigger Thread
    • HTTP request Thread

Many children's shoes are confusing, if JS is single-threaded, then who is going to poll the big event loop events queue? The answer is that the browser will have a separate thread to handle this queue.

Is the Ajax asynchronous request really asynchronous?

Many children's shoes are not clear, since JavaScript is a single-threaded operation, then XMLHttpRequest after the connection is really asynchronous?
The request is actually asynchronous, and the request is made by the browser to open a new thread request (see the previous browser multithreading). When the state of the request changes, if a callback was previously set, the asynchronous thread puts a status change event into the JavaScript engine's event processing queue for processing. When the browser is idle, the out-of-queue task is processed, and the JavaScript engine is always single-threaded to run the callback function. The JavaScript engine is really a single-threaded task queue that can be understood as a queue of normal functions and callback functions.

Summing up, the AJAX request is really asynchronous, the request is a new thread request by the browser, the event callback is placed in the incident Loop Single-threaded event queue waiting to be processed.

SetTimeout (func, 0) Why is it sometimes useful?

Writing JS more children's shoes may find that sometimes adding a settimeout (func, 0) is very useful, why? Is it analog multithreading? Wrong! As already mentioned, JavaScript is JS running in the browser, is a single thread, each window a JS thread , since it is single-threaded, SetTimeout (func, 0) where is the magic? That is to tell the JS engine, after 0ms put the Func into the main event queue, waiting for the current code to execute before execution, note: The focus is to change the code flow , the execution of the Func to wait until the current code execution is completed before execution. That's the magic of it. There are three uses for it:

    • Let the browser render the current changes (many browser UI render and JS execution is placed in one thread, thread blocking will cause the interface to not update rendering)
    • Re-evaluate "script is running too long" warning
    • Change the order of execution
Implementation of non-blocking JS (non-blocking JavaScript)

JS in the browser needs to be downloaded, interpreted and executed in these three steps. The script in the HTML body tag is blocked. In other words, it is downloaded, interpreted, and executed sequentially.

Although Chrome can implement multi-threaded parallel download external resources, such as: script file, image, frame, etc. (CSS is more complex, in IE do not block the download, but Firefox blocked download).

However, because JS is single-threaded, so although the browser can speed up the JS download , but must be executed sequentially (because it is a single thread). So the image image resources in chrome can be downloaded concurrently, but the external JS file concurrent download does not make much sense.

There are two ways to implement non-blocking JS (non-blocking JavaScript): 1. HTML5 2. Dynamic Loading JS

1. Html5defer <script type= "text/javascript" defer src= "foo.js" ></script>Async <script type= "text/javascript" async src= "foo.js" ></script>2. Dynamic Loading JS

Single-threaded asynchronous synchronous blocking non-blocking

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.