JavaScript Async, Stack, event loop, task queue

Source: Internet
Author: User

Overview

We often hear engines and runtime, what is the difference between them?

    • Engine: Interprets and compiles the code, making it a code that can be handed to the machine (runnable commands).
    • Runtime: is the operating environment, it provides some external interface for JS calls to deal with the outside world, such as the browser environment, node. JS environment. Different runtime, will provide different interfaces, for example, in the node. JS Environment, we can require introduce modules, and in the browser, we have window , DOM.

JS engine is single-threaded, as in, it is responsible for maintaining the task queue, and through the mechanism of Event Loop, in order to put the task into the stack execution. The asynchronous processing module in the diagram is provided by the runtime and has a thread that does not interfere with the JS engine. Next, we'll dwell on the diagram: Stacks and task queues

Stack

Now, we're going to run the following code:

function bar() {    console.log(1);}function foo() { console.log(2); far();}setTimeout(() => { console.log(3)});foo();


It is in the stack of the stack, the process of the stack, such as:

Task Queue

Js, there are two types of task queues: the macro task queue (macros tasks) and the Micro tasks queue. A macro task queue can have multiple, micro-task queues with only one. So what is the task that will be divided into which queue?

    • Macro tasks: Script (Global Task), SetTimeout, SetInterval, setimmediate, I/O, UI rendering.
    • Micro tasks: Process.nexttick, Promise, Object.observer, Mutationobserver.

As we mentioned above, when the stack is empty, it will be executed from the task queue and the task is taken. Total 3 steps:

    1. Take a macro task to execute. After execution, the next step.
    2. Take a micro task to execute, after execution, then take a micro task to execute. Until the micro task queue is empty, perform the next step.
    3. Updates UI Rendering.

Event Loop performs the above 3 loops indefinitely, which is the primary control logic for Event loop. The 3rd step (update UI rendering) determines whether the update should be performed immediately, depending on the browser's logic. After all, the cost of updating the UI is large, so it usually takes a long time interval to perform an update.

From the implementation steps, we found that micro-task, received special treatment! Our code starts with the script (Global Task), so once our global task (which belongs to the macro task) executes, the entire micro-task queue is executed as soon as it is completed. Look at an example:

Console.log (' Script start ');Promise.resolve (). Then (() = {Console.log (' P 1 ');}); SetTimeout (() = {Console.log (' SetTimeout ');},0);var s = new Date ();  while (new Date ()-s < 50); //Block 50mspromise.resolve (). Then (() = { Console.log (' P 2 ');}); Console.log (' script ent ');  /*** output ***///One macro taskscript startscript ent/All micro TASKSP 1p 2//One macro task Againsettimeout                  



The reason for the above 50ms blocking is becausesetTimeoutThe delaytime is at least 4ms. To avoid thinkingsetTimeoutIt is because of the delay of 4ms and the later is executed, we add 50ms block. In the micro-task,process.nextTickis a special task, it will be inserted directly into the team head of the Micro task (of course, multipleprocess.nextTickis also first-in, first-out), with the highest priority.


Source: 1190000011198232

JavaScript Async, Stack, event loop, task queue

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.