Review old knowledge, there was a period of time did not review basic knowledge, re-learn, and obtained new knowledge.

  • Asynchronous-origin

    • JS is a single-threaded language that can only do one thing at a time.
    • In the case of waiting operations such as network request Ajax and scheduled task setTimeout, the page cannot be stuck, so asynchronous is required.
    • Asynchrony does not block code execution and is implemented as a callback function.
  • Asynchronous – Event Loop

    • Event Loop, also known as Event Loop or Event polling, is the implementation principle of asynchronous callback.
    • The general process of Event Loop can be understood through the following steps and pictures:
      1. Synchronizes code line by line on the Call Stack;
      2. When asynchrony occurs, it “logs” the Web APIs and waits for opportunities (timing, network requests, etc.).
      3. When the time is right, the Callback to the Web APIs will be moved to the Callback Queue;
      4. If the Call Stack is empty (that is, the synchronized code is finished), the Event Loop starts working.
      5. Callback Queue (if any, move to the Call Stack);
      6. The Event Loop then continues the search

  • Asynchronous – DOM render -> Event Loop

    • In browsers, JS and DOM rendering need to share a thread because JS has the ability to modify the DOM structure. Furthermore, DOM events that trigger DOM rendering should also be asynchronous, using Event loop-based callbacks.
    • DOM render -> Event Loop steps are as follows:
      1. Each time the Call Stack is cleared (that is, each poll ends), the synchronization task is completed.
      2. Both are opportunities for DOM re-rendering, which is required if the DOM structure changes;
      3. Then the next Event Loop is triggered
  • Asynchronous – Microtask -> DOM Render -> Event Loop -> Macro task

    • Macro task:
      • SetTimeout, setInterval, Ajax, DOM events
      • Triggered after DOM rendering
      • Specified by the browser and stored in the Callback Queue
    • Micro tasks:
      • Refers to the Promise, async/await
      • Triggered before DOM rendering
      • Specified by ES6 syntax, stored in the Micro Task Queue
    • When the concept of DOM rendering, macro task and micro task is added to the initial Event Loop, the following more complete Event Loop schematic diagram can be obtained.

Above, ^ _ ^