Comparison of asynchronous programming between Web worker and JS

Source: Internet
Author: User
Tags setinterval

0. speaking from a question
var true ; setTimeout (functionfalse;},+(t) {}alert (' End ');

q, when does the above code alert "end"?
Test: the answer is: never alert.

Parsing: the JavaScript engine is single-threaded and event-triggered Queued. All tasks are queued in accordance with the trigger Time.
In the above example, the queued order states are:

| var t=true; | While (t) {}; | Alert (' End '); |

After 1000ms, the settimeout function also joins the Queue.
While (t) {} infinite loops block a single thread, no matter how short the code execution time is, the subsequent code cannot be executed and blocks.

1. Browser Threads

The browser has so many threads:UI rendering thread (for page rendering),javascript engine thread (for processing js),GUI event triggering thread (for interaction).

Threads that are sometimes turned on:http transport thread , timed trigger thread (timer)

What is the relationship between them?

(1) UI render thread is mutually exclusive to JavaScript engine thread

Because JavaScript can manipulate the DOM of the page, if the UI render thread is not mutually exclusive to the JavaScript engine thread, the JavaScript engine thread makes DOM modifications while the UI rendering thread is rendering the page, resulting in inconsistent Dom State. therefore, when the JavaScript engine thread is running, the UI render thread is in a frozen state.

(2) JavaScript engine thread and GUI event trigger thread (for interactive) Asynchronous

The browser turns on the event-triggering thread, waits for user action, the event-triggering thread resolves to the response event, moves to the JavaScript engine thread, queues up, waits for the JavaScript engine to Process.

(3) the JavaScript engine thread is asynchronous with the HTTP transport thread

Web Get,post and other requests, XHR asynchronous requests are routed through the HTTP transport thread, queued to the JavaScript engine, waiting to be processed.

(4) JavaScript engine thread and timed trigger thread (timer) asynchronous

SetTimeout (), setinterval () is triggered by a thread that is timed by a separate thread, which is routed to the JavaScript engine to wait for processing.

2.XHR Async is a decoy

Let's do an experiment:

Client JS Code

//jquery encapsulated Ajax request, Request Http://localhost:3000/login page$.ajax ({type:"post", Url:"http://localhost:3000/login", DataType:"json", data:{username:username, password:password}, success:function(data) {if(data) {if(data.message== "i202") {alert (' Password is wrong, please re-enter '); Window.location.href= "login"; }Else if(data.message== "i200") {alert (' Landing success '); Window.location.href= "index"; }                Else{alert (' Without this user name '); Window.location.href= "login"; }            } Else{            }        }    }); //There's an infinite loop here .     while(1) {}

Back-end Node. JS Code:

// background response to post function (req, res, Next) {        sleep (+);    Res.send ({status:"success", message: "i200"});      /*  */function  sleep (sleeptime)    {for (var  Start = +new Date; +new date-start <= sleeptime;) { }}

The front desk will never alert ("landing success"). The browser receives a XHR response through an HTTP thread, but goes to the JavaScript thread to wait for Execution. JavaScript is single-threaded and can only handle one task at a Time. The first task is an infinite loop, and all subsequent tasks are Blocked.

XHR asynchronous programming is actually a decoy.

3. Timer time is not allowed (1) time is not allowed 1
SetTimeout (function while (true) {}}, +);        SetTimeout (function () {alert (' end 2 ');        SetTimeout (function () {alert (' end 1 ');}, +);        Alert (' End ');

Run this piece of Code. The result of the operation is alert (' end ') alert (' End 1 ').

The first two timers are not executed at the specified point in Time.

(2) No time 2
SetTimeout (function() {     /**     /)  ; (ten);  SetInterval (function() {     /** /   

Two timers, this would like to achieve the same function: every 10 seconds to trigger a timer.

But in fact, settimeout in 10ms after adding JS execution queue, queued Waiting. So the time interval for every two timer trigger may be > 10ms.

SetInterval every 10s to the JS execution queue to add a setinterval event waiting to be Executed. The preceding SetInterval event may be blocked by its previous events, resulting in a few shots being executed Late. Then the time interval that is not two times the timed time trigger may <10ms.

3.web worker is really multithreaded

Come on, test it out:

Index.html
<! DOCTYPE html>
Fthread.js
// Creating a webworker here is to open a new thread var worker=New worker (' Js/sthread.js '); // Creating child Threads // here to receive the new line Cheng data function (event) {    console.log (event.data);}; // This will trigger the request Worker.postmessage ("begin") to the child process ; // constructs an infinite loop setTimeout (function while (true) {}}, 1000);
Sthread.js
// This takes a new thread and sends a message postMessage (' Hello ') to the main thread; // a previous instance of the implementation to see if blocking setTimeout (function () {console.log (' end 2 ');}, [+]); setTimeout (  function () {console.log (' end 1 ');},console.log (' End ');

Operation Result:

Endhello   // This is the transfer of two thread data, you can not see End1end2

Hello is not blocked by the timer asynchronously because it is running on a child thread. This is Multithreading. Although asynchronous in JS also has the process of processing related operations, but its callback function needs to be executed through the main thread polling, so it is not full multithreading. Webworker is a browser-based engine

Reprint please indicate the source; http://www.cnblogs.com/heshan1992/p/6698069.html

Comparison of asynchronous programming in Web worker and JS

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.