An in-depth look at the browser event loop (code examples)
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>
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
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
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>
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
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
then execute setTimeout and add a task to the timer thread
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)
#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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Every application you run on Windows has a component program to update it. So if you are using Google Chrome or Google Earth, it will run a GoogleUpdate.exe application, check if an update is available, and then update it based on the settings. However, if you no longer see it and instead see a process updater.exe in the Task Manager of Windows 11/10, there is a reason for this. What is Updater.exe in Windows 11/10? Google has rolled out updates for all its apps like Google Earth, Google Drive, Chrome, etc. This update brings

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

What is the Chrome plug-in extension installation directory? Under normal circumstances, the default installation directory of Chrome plug-in extensions is as follows: 1. The default installation directory location of chrome plug-ins in windowsxp: C:\DocumentsandSettings\username\LocalSettings\ApplicationData\Google\Chrome\UserData\Default\Extensions2. chrome in windows7 The default installation directory location of the plug-in: C:\Users\username\AppData\Local\Google\Chrome\User

What should I do if the Google Chrome web page cannot be opened? Many friends like to use Google Chrome. Of course, some friends find that they cannot open web pages normally or the web pages open very slowly during use. So what should you do if you encounter this situation? Let’s take a look at the solution to the problem that Google Chrome web pages cannot be opened with the editor. Solution to the problem that the Google Chrome webpage cannot be opened. Method 1. In order to help players who have not passed the level yet, let us learn about the specific methods of solving the puzzle. First, right-click the network icon in the lower right corner and select "Network and Internet Settings." 2. Click "Ethernet" and then click "Change Adapter Options". 3. Click the "Properties" button. 4. Double-click to open i

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

This tutorial shows you how to find specific text or phrases on all open tabs in Chrome or Edge on Windows. Is there a way to do a text search on all open tabs in Chrome? Yes, you can use a free external web extension in Chrome to perform text searches on all open tabs without having to switch tabs manually. Some extensions like TabSearch and Ctrl-FPlus can help you achieve this easily. How to search text across all tabs in Google Chrome? Ctrl-FPlus is a free extension that makes it easy for users to search for a specific word, phrase or text across all tabs of their browser window. This expansion

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.
