Make a summary every day, persistence is victory!

/** @date 2021-05-28 @description Browser Event Loop */Copy the code

One (sequence)

First we know that JS is a single-threaded, non-blocking language.

Single thread is because the main running environment of JS is the browser, and there are a lot of DOM operations in the browser, if JS is a multi-threaded language, that two threads modify and delete the same DOM at the same time, how to do?

Non-blocking means that when the JS code meets an asynchronous operation during execution, it does not wait for the completion of the asynchronous operation, but suspends it and executes the corresponding callback after the completion of the operation. The Event Loop is used to implement the NON-blocking nature of JS.

Ii (Explanation)

So what is an Event Loop?

A js code in the process of execution, the synchronization code will be executed in sequence in the main thread, with asynchronous code will wait after the completion of the execution, the main thread to continue to perform the synchronization code), the corresponding back to surge into the task queue, wait until the main thread of the synchronization code execution is completed, will go to task queue view, there is no need to perform the callback code is executed, In these callbacks, the synchronous code is executed first, and the asynchronous code is suspended, waiting for the completion of the asynchronous code to be pushed into the task queue, and then checking whether the callback code needs to be executed in the task queue after the completion of the synchronous execution. Such a cyclic process is called an event loop.

Take a look at this code:

console.log(1);
setTimeout(() => {
    console.log(2);
}, 0);
console.log(3);
Copy the code

First sync the execution code console.log(1); , prints 1, then encounters an asynchronous setTimeout, and executes console.log(3) down; , output 3. After the synchronization code is executed, retrieve setTimeout callback execution from the task queue, output 2.

Three (macro task, micro task)

Take a look at the following code:

console.log(1);
setTimeout(() => {
    console.log(2);
}, 0);
const p = new Promise((resolve, reject) => {
    resolve(4);  
});
p.then(val => {
    console.log(val)
});
console.log(3);
Copy the code

As explained, it should print 1,3,2,4, but it actually prints 1,3,4,2;

This is because tasks are also divided into macro tasks and micro tasks. During the execution, all the micro tasks will be completed first, and then macro tasks will be executed.

Macro task:

  1. setInterval;
  2. setTimeout;
  3. setImmediate;
  4. I/O operations;

Micro tasks:

  1. Promise;
  2. MutationObserver;

Iv (Exercise)

Do an exercise:

async function async1() {
  console.log('async1 start');
  await async2();
  console.log('async1 end');
}

async function async2() {
  console.log('async2');
}

console.log('script start');

setTimeout(function () {
  console.log('setTimeout');
}, 0);

async1();

new Promise(function (resolve) {
  console.log('promise1');
  resolve();
}).then(function () {
  console.log('promise2');
});

console.log('script end');
Copy the code
  1. Perform synchronous code outputscript start;
  2. encountersetTimeout, intoTask queueAnd is a macro task;
  3. Execute sync codeasync1();The outputasync1 start;
  4. encounterawaitTo be executed firstawaitThe function after thatasync2; The outputasync2; Code is then pressed inTask queue, and is a microtask;
  5. Execute the synchronization code in Promise, outputpromise1;resolve()After the code is pressed inTask queue, and is a microtask;
  6. Execute synchronization code, outputscript end;
  7. All synchronized code in this loop completes and begins executionTask queueThe callback in step 4 is first pressed into the microtask, outputasync1 end;
  8. Continue to perform the microtask pressed in step 5, outputpromise2;
  9. After executing all microtasks, execute the macro task pressed in step 2 and outputsetTimeout;

Final output: script start, async1 start, async2, promise1, script end, asynC1 end, promise2, setTimeout