preface

As we all know, JS is a single-threaded scripting language, which can only do the same thing at the same time. In order to coordinate events, user interaction, scripting, UI rendering and network processing and prevent the main thread from blocking, Event Loop scheme came into being…

Personal blog: obkoro1.com


Why is JS single threaded?

As a scripting language mainly running in browsers, ONE of the main uses of JS is to manipulate DOM.

If js has two threads operating on the same DOM at the same time, which thread should the browser listen to? How to determine the priority?

To avoid this problem, JS must be a single-threaded language, and that will not change in the future.


Execution stack and task queue

Because JS is a single-threaded language, when it comes to asynchronous tasks (such as Ajax operations), it is not possible to wait for the asynchronous task to complete and then continue to execute. During this time, the browser is idle, which obviously leads to a huge waste of resources.

Execution stack

When a function is executed, the user clicks the mouse once, Ajax completes, an image is loaded, etc., as long as the callback function is specified, these events will enter the task queue and wait for the main thread to read, following the first-in, first-out principle.

To execute a task in the task queue, the executed task is called the execution stack.

The main thread

To be clear, the main thread is a different concept from the execution stack. The main thread specifies which event in the execution stack is now executed.

Main thread loop: that is, the main thread constantly reads events from the stack and executes all synchronized code in the stack.

When an asynchronous event is encountered, instead of waiting for the asynchronous event to return a result, the event is suspended in a separate Queue from the execution stack, called a Task Queue.

When the main thread has finished executing all the code in the stack, it will check to see if there are any tasks in the task queue. If so, the main thread executes those callbacks in the task queue in turn.

If you don’t understand, you can run the code below, or click on the demo

The result is that the three settimeouts will not be executed until a, B, and C have all completed their execution.

SetTimeout (() => {console.log(' task queue function 1')}, 0) for (let I = 0; i < 5000; I++) {console.log('a for loop ')} console.log('a event completes ')} let b = () => {setTimeout(() => {console.log(' task queue function 2')}, 0) for (let i = 0; i < 5000; I++) {console.log('b for loop ')} console.log('b event completes ')} let c = () => {setTimeout(() => {console.log(' task queue function 3')}, 0) for (let i = 0; i < 5000; I++) {the console. The log (' c of a for loop ')} the console. The log (' c event performed ')} a (); b(); c(); // setTimeout will be executed after a, b, and c have all been executedCopy the code

Js asynchronous execution of the operation mechanism.

  1. All tasks are executed on the main thread, forming an execution stack.
  2. In addition to the main thread, there is a “task queue”. Whenever an asynchronous task has a result, an event is placed in the “task queue”.
  3. Once all synchronization tasks in the Execution stack are completed, the system reads the Task queue. Those corresponding asynchronous tasks end the wait state, enter the execution stack and begin execution.
  4. The main thread repeats step 3 above.

Macro and micro tasks:

Asynchronous tasks are divided into macrotasks and microtasks. Tasks registered by different APIS will enter their corresponding queues one by one, and then wait for the Event Loop to push them into the execution stack for execution.

Macrotask:

Script, setTimeout, setInterval, UI rendering, I/O, postMessage, MessageChannel, setImmediate(Node.js environment)

Microtasks:

Promise, MutaionObserver, Process.nexttick (node.js environment)

Event Loop:

In an Event Loop, each Loop is called a TICK and performs the following tasks:

  • The execution stack selects the first macro task to be queued (usuallyscriptOverall code), if so, execute
  • Check whether microtasks exist. If microtasks exist, execute them continuously until the Microtask queue is cleared
  • Update render(every time the event loop, the browser might update the render)
  • Repeat the above steps

Macro Tasks > All Micro Tasks > Macro Tasks, as shown below:

From the picture above, we can see that:

  1. Think of all tasks as two queues: an execution queue and an event queue.
  2. Execution queues are synchronous, event queues are asynchronous, macro tasks are placed in the event list, micro tasks are placed after execution queues, and event queues are placed before.
  3. After the synchronization code is executed, the microtasks that follow the execution list are executed, followed by the macro tasks in the event list

The demo result mentioned above can be interpreted as follows: execute the script macro task first, and then execute the other two timer macro tasks.


Interview question Practice

The following question, many of you should have seen/encountered, re-look will not feel a lot of clarity:

** setTimeout(function () {console.log(1); }); new Promise(function(resolve,reject){ console.log(2) resolve(3) }).then(function(val){ console.log(val); }) console.log(4);Copy the code

According to the analysis of this paper, we can get:

  1. Start by executing script synchronization code

    Perform console.log(2) in new Promise,then do not perform the microtask and then execute console.log(4).Copy the code
  2. After executing the script macro task, execute the microtask, console.log(3). There are no other microtasks.

  3. Execute another macro task, timer, console.log(1).

2,4,3,1.


conclusion

There are many more interview questions like the one above, but they are all very similar. Once you understand the mechanism of the event cycle, these questions will be easy.

Article if have incorrect place welcome everybody to pass by big guy spur! Hope you can have a harvest after watching, if you like it, click on the wave to subscribe to follow/like.

After watching the friends can click a like/follow, your support is the biggest encouragement to me.

Personal blog and nuggets personal homepage, if need to reprint, please put the original link and signature. Code word is not easy, thank you for your support!

If you like this article, please follow my subscription number, long technical road, looking forward to learning and growing together in the future.

The above 2018.6.16

References:

Explain the Event Loop mechanism in JavaScript

The Event Loop in JavaScript

More on the Event Loop