current position:Home>Analysis of operation mechanism of new generation JavaScript

Analysis of operation mechanism of new generation JavaScript

2021-08-27 08:23:40 Xiao Cheng

JavaScript Operating mechanism

Hello everyone , I'm Xiao Cheng's classmate , a Prospective sophomore front-end enthusiasts

This article will take you to learn and understand JavaScript Operating mechanism

May you be true to yourself , love your life

introduction

In some interviews , We may be asked such questions

Briefly JavaScript Operation mechanism of ?

You may also be asked such code

setTimeout(function () {
    
    console.log(' The timer is on ')
});

new Promise(function (resolve) {
    
    console.log(' Do it now for It's a cycle ');
    for (var i = 0; i < 10000; i++) {
    
        i == 99 && resolve();
    }
}).then(function () {
    
    console.log(' perform then Function ')
});

Although these look profound and complex , But if you understand JavaScript Operation mechanism of , These problems can be solved one by one

The outline of this article is attached first , This article will start from this Three aspects Parse JavaScript Operation mechanism of

image-20210819095110499

First of all, let's talk about JavaScript The single thread

1. Why single thread ?

as everyone knows ,JavaScript It is a single-threaded language , It has also brought a lot of criticism , So single thread is so unbearable , Why not design it as multithreaded ?

In fact, this problem appears in JavaScript Of Application scenarios On , We usually use JavaScript To operate DOM Elements , This is no problem now . But let's think about it , If JavaScript Became a multithreaded language , What will happen then ?

Imagine the scene below

a section JS Code Delete DOM Elements , a section JS Code change DOM Element style , They were executed together , What will happen ?

Let's not talk about what the browser should do , I don't even know how to deal with , Then the browser will crash …

To avoid such a situation , JavaScript Designed as a single threaded language

Single thread means , Only one task can be performed at a time , Other tasks need to wait in line

But in order to have multithreading function , There have been many attempts

stay HTML5 In the proposed web worker standard , It provides a complete set of API To allow outside the main thread To execute another thread , But this Doesn't mean the JavaScript Since then, I have the ability of multithreading , At the same time, we can't use it to operate DOM Elements .

stay JavaScript There is also a unique implementation mechanism , It divides the tasks in the main thread into synchronous tasks and asynchronous tasks

2. Why do I need to be asynchronous ?

In order to solve the problem of code blocking caused by single thread

JS It's single threaded , We can imagine a ticket window , There are many people waiting in line at the window for business , and JS You can only process one by one , If a customer has a lot of needs , It takes a long time to handle business , Then the rest of the team will have to wait , It's equivalent to code blocking , Browser Feign death , Wait for the code to execute

Therefore, we have the concepts of synchronous task and asynchronous task

It is necessary to distinguish , Separate those who have been doing business for a long time , Wait until other customers are processed before unified processing

Synchronous tasks and asynchronous tasks are explained in this way

  • Synchronization task : Is a task queued on the main thread , Only the previous task was completed , To perform the next task , for example :console.log
  • Asynchronous task : Do not enter the main thread 、 Handling through event loop mechanism , Register the callback function in the task queue and finally get the result , for example :setTimeout

Learned what synchronization is , What is asynchronous , Let's have a very simple topic

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

Results output 1 3 2

as a result of setTimeout It's an asynchronous task , It needs to be executed after synchronous code execution

Next, let's talk about the core of the operating mechanism : The event loop

3. The event loop

First, we use a diagram to understand the event loop

image-20210818224430488

Its operation mechanism is as follows :

  1. All synchronization tasks are performed on the main thread , Form an execution stack , That is, the blue arrow in the figure above indicates
  2. There is an asynchronous task queue outside the main thread ( The red arrow ), Will wait until the asynchronous task After returning the result Put it in Task queue
  3. When the stack code in the main thread is executed , That is, the synchronization task is completed , will Start reading Task queue code , Then put it into the execution stack to execute
  4. Keep repeating the above three steps , This is the event loop

If you use graphics , It's the one in the picture above Three black arrows , Connected closed loop

in other words : As long as the main thread execution stack is empty , Will read the task queue , The process is cyclical , This mechanism is called event loop

Understand the event loop , Let's make a simple upgrade to the previous question

console.log(1);
setTimeout(()=>{
    console.log(2);},0)
setTimeout(()=>{
    console.log(3);},1000)
setTimeout(()=>{
    console.log(4);},0)
console.log(5);

Output this time 1 – 5 – 2 – 4 – 3

Someone might be right 3 I have doubts about the output of , First, timers are asynchronous tasks , Will be put into the asynchronous task queue first , Need to wait for asynchronous tasks After returning the result , Then put the callback function into the task queue , Wait for the main thread to execute , therefore ,2 and 4 Will be in 3 Output before

4. Asynchronous task queue details

Common events that will be put into the asynchronous task queue

  1. DOM event
  2. Promise
  3. Ajax request
  4. setTimeout and setlnterval
  5. Upload files

As for the time to join the asynchronous task queue , It depends on the current asynchronous task , Not to say that Get the asynchronous task and add it directly to the task queue , Wait until the current asynchronous task is completed and the result is returned , Just put it in the task queue

take setTimeout Come on , Is the need to Wait for the timing to end Then add the callback to the task queue

It can also be understood in combination with the following figure

image-20210819002424355

Understand the task queue , We need to talk again about asynchronous tasks , Macro tasks and micro tasks subdivided

5. Macro task and micro task

There can be multiple queues of macro tasks , There is only one microtask queue

So what is a macro task , What are micro tasks ?

  • The macro tasks are :HTML analysis 、 Mouse events 、 Keyboard events 、 Network request 、 Execution thread js Code and timer
  • Micro task :promise.then,DOM Rendering ,async,process.nextTick

How is it executed ?

  1. When the synchronization task in the execution stack is completed , Do the micro task first

  2. After the execution of the micro task queue , Will read macro tasks

  3. During the execution of the macro task , Encounter microtask , Then join the micro task queue

  4. After the macro task is executed , Read the micro task queue again , In turn, cycle

Draw a picture to help understand

Summarize in a simple sentence : Micro tasks are always executed before macro tasks are executed

image-20210819001618159

Particular attention Yes. : Because the code entry is a script label . therefore , Global tasks are macro tasks

6. actual combat

After knowing so much , Let's look at the classic interview questions

console.log("1");
setTimeout(function () {
    
    console.log("2");
    new Promise(function (resolve) {
    
        console.log("3");
        resolve();
    }).then(function () {
    
        console.log("4");
    });
});
new Promise(function (resolve) {
    
    console.log("5");
    resolve();
}).then(function () {
    
    console.log("6");
});
setTimeout(function () {
    
    console.log("7");
});
setTimeout(function () {
    
    console.log("8");
    new Promise(function (resolve) {
    
        console.log("9");
        resolve();
    }).then(function () {
    
        console.log("10");
    });
});
new Promise(function (resolve) {
    
    console.log("11");
    resolve();
}).then(function () {
    
    console.log("12");
});
console.log("13");

The answer is :1 – 5 – 11 – 13 – 6 – 12 – 2 – 3 – 4 – 7 – 8 – 9 – 10

The first cycle

  • From the global task portal , First Print journal 1
  • Encounter macro task setTimeout , To the asynchronous processing module , Write it down as setTimeout1
  • Meet again promise object , Print journal 5 , take promise.then Join the micro task queue , Remember to do p1
  • Meet again setTimeout To the asynchronous processing module , Write it down as setTimeout2
  • Meet again setTimeout To the asynchronous processing module , Write it down as setTimeout3
  • encounter promise object , Print log 11 , take promise.then Join the micro task queue , Remember to do p2
  • Encountered print statement , Print log directly 13

A total of... Are printed in this cycle :1 – 5 – 11 – 13

Current cycle result

image-20210819084640821

The second cycle

  • First execute the micro task queue p1 and p2 , fifo , Print first 6 Re print 12
  • Micro task event processing completed , Start performing macro tasks setTimeout1
  • Encountered print statement , Print log directly 2
  • Meet again promise object , Print log 3, take promise.then Join the micro task queue , Remember to do p3

The second cycle ends

The current running diagram is

image-20210819084924330

The third cycle

  • First execute the micro task queue , Print log 4
  • Micro task processing completed , Execute macro task setTimeout2
  • Encountered print statement , Direct output 7

The cycle ends

image-20210819085314165

The fourth cycle

  • The micro task queue is empty , Execute macro task setTimeout3
  • Encountered print statement , Print log 8
  • encounter promise object , Execute the print statement , Print 9
  • take promise.then Join the micro task queue Remember to do p4

image-20210819085545680

The fifth cycle

  • First, empty the micro task queue , Execute the print statement , Print 10
  • completion of enforcement

That's about JavaScript The whole content of the operating mechanism , I hope I can get something

Thank you very much for reading , Your comments are welcome , If you have any questions, please point out , thank you !

copyright notice
author[Xiao Cheng],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827082334598o.html

Random recommended