current position:Home>Analysis of event loop mechanism in JavaScript

Analysis of event loop mechanism in JavaScript

2022-04-29 05:34:4151CTO

Preface

JavaScript Is a single threaded weakly typed language , But we are developing , We often encounter some processing operations that need to be asynchronous or waiting .
similar ajax, Also, or ES6 In the new promise Operation is used to handle some callback functions, etc .

Concept

stay JavaScript During code execution , It can be divided into synchronous queue and asynchronous queue .

  1. Synchronization tasks are similar to what we often call immediate execution functions , You don't need to wait, you can do it directly , You can directly enter the main thread to execute , Similar to normal function calls, etc .

  2. Asynchronous queues are asynchronous execution functions , similar ajax request , In the process of launching , Will enter an asynchronous queue , When loading into a task , Need to wait , Only then can the return value be processed .

Take a chestnut

The following code , We can first understand some basic principles of the event loop mechanism


console.log('1');
setTimeout(function() {
  console.log('4');
}, 0);
Promise.resolve().then(function() {
  console.log('2');
}).then(function() {
  console.log('3');
});
console.log('5');

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

We print the code to the console , The output is :1,5,2,3,4

We know , stay JavaScript in , It's like a timer , as well as ES6 Newly added promise It's an asynchronous function , Back to the concept of queues we mentioned above , It's not hard to get out ,1 and 5 Queue for synchronous execution

After executing the code in the synchronization queue , Then execute the code in the asynchronous queue .

TIP

Parsing asynchronous queues promise And timer , We found that , Timer setTimeout Yes, executed on promise, Here we introduce JavaScript Macro tasks in the specification **(Macro Task**) And micro tasks **(Micro Task)** The concept of

stay JavaScript in , Macro tasks include :script( The overall code )、setTimeout、setInterval、I/O、UI Interactive events 、setImmediate(Node.js Environmental Science )

Micro task :Promise、MutaionObserver、process.nextTick(Node.js Environmental Science )

Go back to the above timer and promise The problem of , Now we know ,JavaScript in , When there are asynchronous queues , Prioritize micro tasks , Then execute the macro task

Another chestnut

If there is an asynchronous queue in the asynchronous queue , What do we need to do with

console.log(1);
setTimeout(function() {
  console.log(5);
}, 10);
new Promise(resolve => {
    console.log(2);
    resolve();
    setTimeout(() => console.log(3), 10);
}).then(function() {
    console.log(4);
})
console.log(6);

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

Execute the code into the console , The printing order is :1,2,6,4,5,3

  • Different from the example 1 In the middle of promise, Print 2 Is prior to 6 Executive , From this we can know that ,new Promise In the process of execution , In the absence of execution resolve perhaps rejected front , The code executed is the code in the synchronization queue .

  • Look again 4,5,3 Execution order of , Performing micro tasks promise Execution callback resolve after , Corresponding then Execute now

  • In the printout , Timer 5 Take precedence over ----> It's a micro task promise Macro task timer in 3, Timer 5 This macro task is in promise The micro task queue is then added , stay promise Execution completed then After callback ,promise The macro task in is added to the queue , So in the timer 5 After performing

summary

stay JavaScript in , Macro tasks include :script( The overall code )、setTimeout、setInterval、I/O、UI Interactive events 、setImmediate(Node.js Environmental Science )

Micro task :Promise、MutaionObserver、process.nextTick(Node.js Environmental Science );

In the process of execution , Synchronization code takes precedence over code in other task queues ,
Timer ,promise Such tasks , In the process of execution , Will join the queue first ,
After executing the synchronization code , Then according to the classification of macro task and micro task , Execute the micro task queue first , Then execute the macro task queue .

Article personal blog address : JavaScript Event cycle mechanism of

Welcome to the official account : Program ape boo , Update some front-end introductory articles from time to time

It's not easy to create , Please indicate the source and the author of the reprint .

copyright notice
author[51CTO],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/116/202204261035256367.html

Random recommended