Single-threaded JS engine

Source: Internet
Author: User
Tags setinterval

First to consider a question, JS is single-threaded? Why does single-threaded JavaScript allow Ajax to send and callback requests asynchronously, and settimeout also look like multithreaded? There are also concepts such as Non-blocking IO, event loop, and so on.

Directory:

    1. JS Single Thread
    2. Browser multithreading
    3. Application Scenarios for SetTimeout (func, 0)
    4. SetTimeout and SetInterval
    5. Resources
    6. TODO: Next, comb the concurrency model of JS and the Event Loop

Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/EventLoop

Http://www.ruanyifeng.com/blog/2014/10/event-loop.html

1. JS Single Thread

The browser has only one thread running the JavaScript program at any time. Single-threaded, that is, only specific code can execute at a particular time and block other code.

and the browser is event-driven (Event-driven), you can regard the event as a browser assigned to the JS engine task,

These tasks may come from a block of code that the JS engine is currently executing, such as calling SetTimeout () to add a task;

or other threads from the browser kernel, such as the interface element mouse click event, timer time arrival notification, asynchronous request status change notification (a mouse click, a timer firing, or an xmlhttprequest completing),

From a code perspective, a task entity is a variety of callback functions. Because the JS engine is single-threaded, these tasks have to queue (join the JS engine processing queue), waiting to be executed by the JS engine.

    • Benefits:

If multi-threading, then deleting or creating DOM elements requires communication between the threads.

Therefore, single-threaded simple, no need to consider thread synchronization, no thread switching maintenance overhead, save memory.

2. Browser multithreading

The browser kernel implementation allows multiple threads to execute asynchronously, and these threads mate with each other in the kernel to maintain synchronization.

The browser kernel may have the following threads:

Resident Thread:

    • Interface Rendering Thread
    • Event Response Thread

Terminated thread after execution:

    • HTTP request Thread
    • Timer thread

A diagram illustrates how the single-threaded JS engine communicates with other threads:

    • JS engine thread vs. interface Render thread: Mutex

The interface rendering 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) is triggered by an operation.
JavaScript scripts manipulate DOM elements, and if you render the interface while modifying the attributes of these elements, 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 in the script, such as adding nodes, deleting nodes, or changing the appearance of the nodes, are not immediately reflected, and will be stored in a queue, where the JavaScript engine is idle for a chance to render.

    • Event Trigger Thread

User Click Mouse-"triggered by the browser event trigger thread capture-" to form a mouse click event added to the JS engine processing queue End

    • Timed Trigger Thread

The timer counter is not counted by the JS engine, because the JS engine is single-threaded and depends on the external counter if it is not remembered when it is in a thread-blocking state.

A timer is simply a plan code that executes at some time in the future, and the timing of execution is not guaranteed.

It works by specifying a time interval that indicates when the code for the timer is inserted into the processing queue of the JS engine, rather than when the code is executed. The time it waits is based on the number of messages waiting in the queue.

    • Ajax asynchronous requests

The browser opens a new thread request, and when the request state changes, if the callback is set (that is, the callback function set in onReadyStateChange), the asynchronous thread puts the state change event into the processing queue at the end of the JS engine waiting to be processed.

3. Application Scenarios for SetTimeout (func, 0)

It tells 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.

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

In the following example, clicking the button will show "Calculating ..." If you delete settimeout. Because the redraw event is entered into the event queue, it cannot be refreshed until the last long operation is executed.

1<button id= ' do ' > doLongCalc!</button>2<div id= ' status ' ></div>3<div id= ' result ' ></div>4  5  6$ (' #do '). On (' click ',function(){7   8$ (' #status '). Text (' Calculating ... ');//This will trigger the fired of the redraw event, but will be placed in the queue until long () is executed. 9   Ten   //without set timeout, user'll never see "calculating ..." One   //long ();//Perform lengthy tasks, block A     -   //with set timeout, works as expected -SetTimeout (Long, 50);//with a timer, approximately 50ms executes long tasks after, put into the execution queue, but after redraw, according to the FIFO principle the    -  }) -    -    +    - function Long(){ +   varresult = 0 A    for(vari = 0; i<1000; i++){ at      for(varj = 0; j<1000; J + +){ -        for(vark = 0; k<1000; k++){ -result = result + i+j+k -       } -     }  -   } in$ (' #status '). Text (' calclation done ')//Have to is in here for this example. Or else it'll always run instantly. This is the same as passing it a callback -}
View Code

4. settimeout and SetInterval

1 setTimeout (function() {2         */**/3         SetTimeout (Arguments.callee, ten); 4 },; 5 6 setinterval (function() {7         */**  8 }, 10);
View Code

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

5. References

In-depth understanding of javascript timing mechanisms

JavaScript is a single-threaded in-depth analysis

How JavaScript Timers work

JavaScript Advanced Programming (third Edition) 22.3 Advanced Timers

Single-threaded JS engine

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.