Summarize the basic JavaScript concept (ii): Event queue loop

Source: Internet
Author: User

Problems:

1, JS engine is a single thread, how to complete the event loop?

2. Why is the timer function not accurate?

3. What is the connection and difference between callback and async?

4. What is the change in the ES6 event cycle? What's in node?

5. What are the difficulties of asynchronous control? What are the solutions?

Second, event queue cycle

(i), browser thread

The JavaScript engine runs on an event-driven single-threaded run, and the browser, whenever only and only one thread is running a JavaScript program, waits for the task in the task queue to arrive and then handle it.

The kernel of the browser is multithreaded, and they work together with each other under the control of the kernel, and a browser implements at least three resident threads: the JavaScript engine thread, the GUI rendering thread, and the browser event thread.

The GUI rendering thread is responsible for rendering the browser interface, which executes when the interface needs to be redrawn (Repaint) or when a return (Reflow) is caused by an operation. The GUI render thread is mutually exclusive to the JavaScript engine, and when the JavaScript engine executes, the GUI thread is suspended, and the GUI update is saved in a queue and executed immediately when the JavaScript engine is idle. So the rendering operation consumes particularly large.

(ii), Event type and queue


Event Loop: The engine creates an infinite loop similar to while (true), and each time the loop body is executed is called a Tick. The process of each Tick is to see if the event is pending, and if so, take the relevant event and the callback function into the execution stack by the main thread. The pending events are stored in a task queue, that is, each Tick checks to see if there are tasks in the task queue that need to be performed .

Task queue: An asynchronous operation adds a related callback to the task queue. Different asynchronous operations are added to the task queue at different times, such as OnClick, setTimeout, and Ajax processing in different ways, these asynchronous operations are performed by the browser kernel's WebCore, WebCore contains 3 kinds of WebAPI, respectively, the DOM Binding, network, timer module.

The onclick is handled by the DOM Binding module of the browser kernel, and when the event is triggered, the callback function is immediately added to the task queue.
SetTimeout will be deferred by the timer module of the browser kernel, and the callback function will be added to the task queue when the time arrives.

The reason why the JS timer is inaccurate:

1. Callback execution of an asynchronous function blocks the next loop tick. 2, the time accuracy of the browser varies.

Ajax is handled by the Web module of the browser kernel, and the callback is added to the task queue after the network request has finished returning.

Main thread: JS has only one threading, which is called the main path. The event loop is executed only after the execution of the code in the main thread is stacks. Therefore, the code that executes in the main thread takes too long to block the execution of the event loop, and it blocks the execution of the asynchronous operation. Only when the main thread is stacks empty (that is, after the synchronization code is executed) does the event loop observe the event callback to be executed, and when the event loop detects that there is an event in the task queue, it takes out the relevant callback into the execution stack by the main thread.

In this process, the way to improve page responsiveness is to reduce the number of main thread synchronization codes, and to transfer unimportant code to the event loop phase.

(iii), ES6 's task queue

The event queue has been modified so that asynchronous callbacks can be executed earlier, with each tick gap prioritizing the task queue without queuing to the end of the event queue. A must-have exam to look at the order of execution:

Promise instances have three states: Wait, resolution, reject. The resulting asynchronous event execution is hung as a task queue at the end of the current tick loop.

(iv) Event loops in Nodo
The event loop of the JS engine requires the hosting environment to provide queue maintenance, and node is out of the browser, using different ways to interact with the underlying system.

观察者:引擎在每个循环过程中询问观察者是否有要处理的事件。

Under window, the Observer is based on the completion of the IOCP listener event, and is created under *nix based on multithreading.

An asynchronous execution API, such as process, is added to node. Nexttick () and setimmiediate.
Process The callback function of Nexttick () is stored in an array, and setimmiediate is stored in a linked list.
In each round of the loop, the callback function in the Nexttick array is executed, and then the callback in the Setimmiediate list is executed.

(v) Handling of asynchronous events
There are some problems in the processing of asynchronous events, such as execution time, uncertain order, callback hell, error difficult to catch location and so on.

1. jquery Deferred Queue module
JQ on the basis of the deferred queue module, the simulation realizes the promise similar method. You can do chain callbacks and delay access.
2, ES6 Promise
Promise instance resolution can not be changed, solve the trust problem. You can access the state of an asynchronous event at any time using a chained callback. Promise can control the execution of a callback in its own logic, rather than handing the callback over to the other side. Async is still not resolved from the substance.
3, Generator
The generator function implements true asynchronous control that switches the execution environment and passes variables between execution environments to implement collaborative function threads.
The well-known co modules, combined with promise and generator, enable synchronous coding of asynchronous processes.
4. Async function
The ES2017 standard introduces an async function that makes asynchronous operations easier. Is the syntactic sugar of the Generator function.
The node framework KOA uses the latest async processing asynchronous process to make the coding more streamlined and streamlined.

Recommended Reference books:

"The Nodejs of the layman"

The Insider of jquery technology

The Insider of WebKit technology

"JavaScript you don't know."

 

Summarize the basic JavaScript concept (ii): Event queue loop

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.