preface

Today, I had an exchange of advanced development skills with my colleague, who asked about Event Loop. There was no answer at that time, so I sorted it out after going home. Keep that in mind.

concept

An Event Loop is a mechanism in a browser or Node that allows javaScript to run in a single thread without blocking, and is often used asynchronously. In JavaScript, tasks are divided into two types: macrotasks, also known as tasks, and microtasks.

Macro task

Macro tasks include Script (overall code), setTimeout, setInterval, setlmMediate, L /O, and UI Rendering

Micro tasks

Micro tasksincludingpromise,Qbject observe,Mutation ObserverA microtask is a follower, always followingThe currentThe macro task is followed by the code executing to a microtask, one after another

Examples show

Let’s look at the following code

console.log('script start' );
 / / macro task
setTimeout( function () {
  console.log('setTimeout' );
}, 0);
  // The microtask follows the current macro
Promise. resolve().then(function () {
  // The microtask follows the current macro task with the stone surface
  console.log('promise1');
}).then(function () {
  // The microtask follows the current macro task
  console.log('promise2');
});
console.log('script end');
Copy the code

In the above code, the first flood task is script (overall code), so the output of script start and script end is priority. So promisE1 and promise2 and then in the second event loop we have the macro task setTimeout so setTimeout is printed so the final output is

And I’ve drawn a picture here to make it easier for you to understand

Little practice

Here are two exercises you can do manually to understand how it works

Title 1

The output is 3, 4, 8, 5, 2

Topic 2

The output is