Preface:

Simple in depth: this article as far as possible (dare not guarantee) to be easy to understand the principle of explanation, to avoid everyone into too theoretical, obscure, want to understand a problem, with several problems of embarrassment. Guarantee (dare to guarantee) that you will gain something, if not, then please read it several times, by the way, use your cute little hands. Learning without thought is useless; thought without code is perilous. Without further ado, let’s get down to business.

JS execution mechanism:

Know what it is and why. As we all know, JS is a single-threaded language from its inception. If you want to check the scriptures, please go to ruan Yifeng’s personal website. The code is executed from top to bottom, line by line, and if one line fails, the rest of the code will not execute. Synchronous code is executed before asynchronous code is executed. Asynchrony is based on callback, and event-loop is the principle of asynchrony.

Asynchronous scenario:

  • 1. Timer: setTimemout/setInterval. A: macroTask.
  • 2. Event listening: DOM operation, event-driven, not asynchronous, but by event-loop mechanism implementation. A: macroTask.
  • 3.Ajax: Proxy XMLHttpRequest sends requests to implement local updates. A: macroTask.
  • Promises: ES6, syntax sugar, asynchronous programming provides a unified interface, chained writing, ajax callback hell problem. MicroTask, slightly task
  • 5.Asyn/Await: ES7, grammar sugar. macroTask
  • Publish-subscribe pattern: publish/subscribe pattern. Avant-garde thinking, better user experience.

Let’s first understand the implementation principle of event-loop. Other Ajax, Promise, Async/Await, publish-subscribe pattern will be updated as necessary.

The Event – loop demo figure

The sample code

Example 1:

1: setTimeout(() => {2: console.log('asynchronous2') :3:}, 500); Log ('synchronization1') 4: setTimeout(() => {5: console.log('asynchronous1') 6:}, 100); 7: setTimeout(() => {8: console.log('asynchronous3') 9:}, 100); 10: the console. The log (' synchronization2 ')Copy the code

Result: 1: print :synchronization1, synchronization2, 2: print :asynchronous1, asynchronous3, 3: print :asynchronous2

Example 2:

1: console.log('synchronization1') 2: const BTN = document.getelementById (' BTN ') 3: Btn.addeventlistener ('click', function () {4: console.log('dom:asynchronous') 5:}) 6: console.log('synchronization2')Copy the code

Synchronization1, synchronization2 Click the button to print dom:asynchronous

thinking

So how does the code in Examples 1 and 2 actually work? What does this have to do with it. Guest officer don’t worry, and read the following. Example 1 code is an example

  • 1: Throw the first line of synchronization code to the Call stack, print “‘synchronization1’ “, and empty the current Call stack
  • 2: The second line setTimeout asynchronous code, throw into the Web API,Record the current timer time and the code to be executed. The difference in Example 2 is that the click event is logged in the Web API.
  • 3: The sixth line of synchronization code is thrown to the Call stack, where the browser prints “synchronization2” and empties the current Call STAC
  • 4: The current call stack is empty and no task is waiting to be executed. Once the synchronous code has been executed, the Event-loop poller will be started (dom rendering will be tried first if dom rendering is involved, since dom manipulation is not involved in this example) to find whether callback Quene has a task queue. Others are fished out and thrown into the Call Stack for execution. So how do callback Quene queues come from? It involves asynchronous code in the Web API. According to the timer definition of the length of time and code shun, such as the example code will in turn"Asynchronous1" (minimum time), "100ms"/" asynchronous3 "(minimum time)," 3ms "/" asynchronous2 "(maximum wait time)Web API throws asynchronous code into callback Quene. If the Call Stack is empty, continue the event-loop polling mechanism.The code in Example 2 differs in that the execution code is thrown to the callback Quene when the click event is triggered.