js event loop mechanism eventLoop

Event loop mechanism EventLoop

Event Loop is an event loop, which is a mechanism to solve the problem of single-thread running blocking of JavaScript.

1. JS execution mechanism

When we learn js, we all know that js is single-threaded. If it is multi-threaded, it will cause a problem. If you operate the DOM at the same time, you will not know what to do if you add and delete JS. So this language is single-threaded, but With the arrival of HTML5, js also supports multi-threaded webWorker, but it does not allow DOM manipulation.

Single thread means that all tasks need to be queued, and subsequent tasks need to wait for the previous tasks to be executed before they can be executed. If the previous tasks take too long, the subsequent tasks will need to wait. Some tasks do not need to wait from the user's perspective. The task will keep waiting, which is unacceptable from an experience perspective, so the concept of asynchronous appeared in JS.

2. Synchronous tasks and asynchronous tasks

Synchronous task: It is a task that gets the result immediately after calling it. The synchronous task is queued for execution on the main thread. The next task can only be executed after the previous task is executed;

Asynchronous task: It is a task that cannot get the result immediately and requires additional operations to expect the result. The asynchronous task does not enter the main thread but enters the "task queue" (task queue). Only the "task queue" notifies the main thread that a certain When an asynchronous task can be executed, the task will enter the main thread for execution. The asynchronous task execution queue first executes the macro task, then clears all micro tasks in the current macro task , and then proceeds to the next tick to form a loop.

Asynchronous tasks can be divided into the following two types (ES6):

  • 1. Macro task
    script (overall code), setTimeout, setInterval, postMessage, Ajax

  • 2. Microtask
    Dom operation, Promise, MutaionObserver, process.nextTick (Node.js environment)

Insert image description here

example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
   // 这里整体的script代码作为第一个宏任务执行
    async function Prom() {
    
    
      console.log('Y')
      await Promise.resolve() //微任务3   await之后的代码都将作为微任务进入任务队列
      console.log('X') 
    }
    setTimeout(() => {
    
     // 宏任务2
      console.log(1)
      Promise.resolve().then(()=>{
    
      // 微任务4
        console.log(2)
      })
    }, 0)
    setTimeout(() => {
    
     // 宏任务3
      console.log(3)
      Promise.resolve().then(()=>{
    
    // 微任务5
        console.log(4)
      })
    }, 0)
    Promise.resolve().then(()=>{
    
    // 微任务1
      console.log(5)
    })
    Promise.resolve().then(()=>{
    
    // 微任务2
      console.log(6)
    })
    Prom()
    console.log(0)
    // 结果 Y 0 5 6 X 1 2 3 4
  </script>
</body>
</html>

***Result analysis: ***The first thing that must be executed is the synchronization task, that is, calling the Prom method to output Y, and then the last section outputs 0; because the overall script code is executed as the first macro task, it must be cleared at this time For all the following microtasks 1, 2, and 3, since the Prom method is called after microtasks 1 and 2, microtask 3 is after microtasks 1 and 2. At this time, a loop ends, the next execution of macro task 2 begins, and then the internal micro task 4 is executed. Continue to the next macro task 3 and micro task 5.

Guess you like

Origin blog.csdn.net/qq_45331969/article/details/131701902