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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools