Home  >  Article  >  Web Front-end  >  An in-depth look at the browser event loop (code examples)

An in-depth look at the browser event loop (code examples)

不言
不言forward
2018-11-12 17:06:451857browse

This article brings you an in-depth understanding of the browser event loop (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The browser's event loop is something that the front-end is very familiar with and is something that comes into contact with every day. But I used to memorize it by rote: The event task queue is divided into macrotask and microtask. The browser first takes out a task from the macrotask for execution, then executes all the tasks in the microtask, and then goes to the macrotask to take out a task for execution... ., and this cycle continues. But for the following code, I have been confused. SetTimeout belongs to macrotask. According to the above rules, setTimeout should be taken out and executed first, but I was slapped in the face by the execution result.

<script>
    setTimeout(() => {
        console.log(1)
    }, 0)
    new Promise((resolve) => {
        console.log(2)
        resolve()
    }).then(() => {
        console.log(3)
    })
    // 我曾经的预期是:2 1 3
    // 实际输出:2 3 1
</script>

After carefully reading other people’s introduction to task queues, I realized that the js code executed synchronously is actually a macrotask (to be precise, the code in each script tag is a macrotask), so the above It is said in the rules that there is no problem in first taking out a macrotask and executing .
Many articles on the Internet explain it like the above. I have always thought that this is HTML's specification of the event loop, and we just remember it. It wasn't until I recently read the article by Mr. Li Yincheng (see the reference link at the end of the article) that I suddenly realized that the articles I had read before did not clearly analyze the browser's multi-threading model from the perspective of it, so we think that the browser's event loop is Based on the above convention, this is actually the result of the browser's multi-threading model.

The essence of macrotask

Macrotask is essentially a message queue for communication between multiple threads of the browser
In chrome, each page corresponds to one Process, which has multiple threads, such as js thread, rendering thread, io thread, network thread, timer thread, etc. The communication between these threads is by adding a task (PostTask) to the other party's task queue. realized.

Various threads in the browser are resident threads. They run in a for infinite loop. Each thread has its own task queues. The thread itself or other threads may send messages to these through PostTask. The task queue adds tasks, and these threads will continuously take out tasks from their own task queues for execution, or they will sleep until the set time or someone wakes them up when PostTask.

It can be simply understood that each thread of the browser is constantly taking out tasks from its own task queue, executing them, taking out the tasks again, and executing them again, and this continues in an infinite loop.

Take the following code as an example:

<script>
    console.log(1)
    setTimeout(() => {
        console.log(2)
    }, 1000)
    console.log(3)
</script>
  1. First, the code in the script tag is put into the task queue of the js thread as a task, the js thread is awakened, and then Take out the task and execute it

  2. First execute console.log(1), then execute setTimeout, add a task to the timer thread, and then execute console.log(3). At this time, the js thread The task queue is empty, and the js thread goes to sleep

  3. After about 1000ms, the timer thread adds a scheduled task (timer callback) to the js thread's task queue, and the js thread is awakened again , execute the scheduled callback function, and finally execute console.log(2).

As you can see, the so-called macrotask does not mean that the browser defines which tasks are macrotask. Each thread of the browser just faithfully circulates its own task queue and executes it continuously. It's just a task.

microtask

Compared with macrotask, which is an "illusion" caused by the browser's multi-threading model, microtask is a queue that does exist. Microtask belongs to the current thread, not other threads PostTask. The task is just delayed (to be precise, it is executed after the currently executed synchronization code), such as Promise.then and MutationObserver. This is the case.

Take the following code as an example:

<script>
    new Promise((resolve) => {
       resolve()
       console.log(1)
       setTimeout(() => {
         console.log(2)
       },0)
    }).then(() => {
        console.log(3)
    })
    // 输出:1 3 2
</script>
  1. First, the code in the script tag is put into the task queue of the js thread as a task, the js thread is awakened, and then Take out the task and execute

  2. and then execute new Promise and resolve in Promise. After resolve, the then callback function of promise will be used as a task that needs to be delayed and placed in all currently executed synchronizations. After the code

  3. then execute setTimeout and add a task to the timer thread

  4. At this time, the synchronization code is executed, and then the delayed execution is executed The task, that is, the then callback function of promise, is to execute console.log(3)

  5. #Finally, the task queue of the js thread is empty, and the js thread goes to sleep. After about 1000ms, The timer thread adds a scheduled task (timer callback) to the js thread's task queue, and the js thread is awakened again and executes the scheduled callback function, namely console.log(2).

总结

通过上面的分析,可以看到,文章开头提到的规则:浏览器先从macrotask取出一个任务执行,再执行microtask内的所有任务,接着又去macrotask取出一个任务执行...,并没有说错,但这只是浏览器执行机制造成的现象,而不是说浏览器按照这样的规则去执行的代码。
这篇文章中的所有干货都来自李银成大佬的文章,我只是按照自己的理解,做了简化描述,方便大家理解,也加深自己的印象。
最后,看了这篇文章,大家能够基于浏览器的运行机制,分析出下面代码的执行结果了吗(ps:不要用死记硬背的规则去分析哟)

console.log('start')

const interval = setInterval(() => {  
  console.log('setInterval')
}, 0)

setTimeout(() => {  
  console.log('setTimeout 1')
  Promise.resolve()
      .then(() => {
        console.log('promise 3')
      })
      .then(() => {
        console.log('promise 4')
      })
      .then(() => {
        setTimeout(() => {
          console.log('setTimeout 2')
          Promise.resolve()
              .then(() => {
                console.log('promise 5')
              })
              .then(() => {
                console.log('promise 6')
              })
              .then(() => {
                clearInterval(interval)
              })
        }, 0)
      })
}, 0)

Promise.resolve()
    .then(() => {  
        console.log('promise 1')
    })
    .then(() => {
        console.log('promise 2')
    })
// 执行结果
/*  start
    promise 1
    promise 2
    setInterval
    setTimeout 1
    promise 3
    promise 4
    setInterval
    setTimeout 2
    promise 5
    promise 6
*/


The above is the detailed content of An in-depth look at the browser event loop (code examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete