search
HomeWeb Front-endJS TutorialDetailed explanation of JavaScript event loop mechanism

This article shares with you relevant knowledge points about the JavaScript event loop mechanism. Friends who are interested can learn and refer to it.

As we all know, JavaScript is a single-threaded language. Although Web-Worker was proposed in html5, this has not changed the core of JavaScript being single-threaded. See this passage in the HTML specification:

To coordinate events, user interaction, scripts, rendering, networking, and so forth, user agents must use event loops as described in this section. There are two kinds of event loops: those for browsing contexts, and those for workers.

To coordinate events, user interaction, scripting, UI rendering, and network processing, user engines must use event loops. Event Loop consists of two types: one based on Browsing Context and one based on Worker, both of which run independently. The following article uses an example to focus on the event loop mechanism based on Browsing Context.

Let’s take a look at the following JavaScript code:

console.log('script start');

setTimeout(function() {
 console.log('setTimeout');
}, 0);

Promise.resolve().then(function() {
 console.log('promise1');
}).then(function() {
 console.log('promise2');
});

console.log('script end');

First guess the output sequence of this code, then enter it in the browser console to see if the actual output sequence matches yours. Is the guessed order consistent? If so, it means that you still have a certain understanding of the JavaScript event loop mechanism. Keep reading to consolidate your knowledge; and if the actual output order is inconsistent with your guess, Then the following part of this article will answer your questions.

Task Queue

All tasks can be divided into synchronous tasks and asynchronous tasks. Synchronous tasks, as the name suggests, are tasks that are executed immediately. Synchronous tasks generally enter the main thread directly for execution; and Asynchronous tasks are tasks that are executed asynchronously, such as ajax network requests, setTimeout timing functions, etc., which are all asynchronous tasks. Asynchronous tasks are coordinated through the task queue (Event Queue) mechanism. The following figure can be used to roughly explain the specific situation:

# Synchronous and asynchronous tasks enter different execution environments respectively. The synchronous tasks enter the main thread, that is, the main execution stack, and the asynchronous tasks enter the main thread, that is, the main execution stack. Enter the Event Queue. If the tasks in the main thread are empty after execution, the corresponding tasks will be read from the Event Queue and pushed to the main thread for execution. The continuous repetition of the above process is what we call Event Loop.

In the event loop, each loop operation is called a tick. By reading the specification, we can know that the task processing model of each tick is relatively complex, and its key steps can be summarized as follows:

  • Select the oldest task that enters the queue first in this tick. If there is one, execute it (once)

  • Check whether Microtasks exist, if they exist Then continue to execute until the Microtask Queue is cleared

  • Update render

The main thread repeats the above steps

You can use a picture to illustrate the process:

I believe someone will want to ask, what are microtasks? The specification stipulates that tasks are divided into two categories, namely Macro Task (macro task) and Micro Task (micro task), and after each macro task is completed, all micro tasks must be cleared. The Macro Task here is also what we often call task. Some articles do not distinguish between them. The tasks mentioned in the following articles are all regarded as macro tasks.

(macro)task mainly includes: script (overall code), setTimeout, setInterval, I/O, UI interactive events, setImmediate (Node.js environment)

microtask mainly includes: Promise, MutaionObserver, process.nextTick (Node.js environment)

setTimeout/Promise and other APIs are task sources, and what enters the task queue is the specific execution task specified by them. Tasks from different task sources will enter different task queues. Among them, setTimeout and setInterval have the same origin.

Analysis of sample code

There are thousands of words, so it is better to explain it clearly with examples. Below we can follow the specifications and analyze the above example step by step. First, post the example code (to save you from scrolling up).

console.log('script start');

setTimeout(function() {
 console.log('setTimeout');
}, 0);

Promise.resolve().then(function() {
 console.log('promise1');
}).then(function() {
 console.log('promise2');
});

console.log('script end');

The overall script enters the main thread as the first macro task, encounters console.log, and outputs script start

  • Encounters setTimeout, and its callback function is distributed to When

  • encounters a Promise in the macro task Event Queue, its then function is assigned to the micro task Event Queue and is recorded as then1. Then it encounters the then function again and assigns it to the micro task Event Queue. In the task Event Queue, it is recorded as then2

  • When it encounters console.log, it outputs script end

##At this point, it exists in the Event Queue Three tasks, as shown in the following table:

Macro taskMicro task setTimeoutthen1-then2
  • 执行微任务,首先执行then1,输出 promise1, 然后执行 then2,输出 promise2,这样就清空了所有微任务

  • 执行 setTimeout 任务,输出 setTimeout 至此,输出的顺序是:script start, script end, promise1, promise2, setTimeout

so,你猜对了吗?

看看你掌握了没

再来一个题目,来做个练习:

console.log('script start');

setTimeout(function() {
 console.log('timeout1');
}, 10);

new Promise(resolve => {
 console.log('promise1');
 resolve();
 setTimeout(() => console.log('timeout2'), 10);
}).then(function() {
 console.log('then1')
})

console.log('script end');

这个题目就稍微有点复杂了,我们再分析下:

首先,事件循环从宏任务 (macrotask) 队列开始,最初始,宏任务队列中,只有一个 scrip t(整体代码)任务;当遇到任务源 (task source) 时,则会先分发任务到对应的任务队列中去。所以,就和上面例子类似,首先遇到了console.log,输出 script start; 接着往下走,遇到 setTimeout 任务源,将其分发到任务队列中去,记为 timeout1; 接着遇到 promise,new promise 中的代码立即执行,输出 promise1, 然后执行 resolve ,遇到 setTimeout ,将其分发到任务队列中去,记为 timemout2, 将其 then 分发到微任务队列中去,记为 then1; 接着遇到 console.log 代码,直接输出 script end 接着检查微任务队列,发现有个 then1 微任务,执行,输出then1 再检查微任务队列,发现已经清空,则开始检查宏任务队列,执行 timeout1,输出 timeout1; 接着执行 timeout2,输出 timeout2 至此,所有的都队列都已清空,执行完毕。其输出的顺序依次是:script start, promise1, script end, then1, timeout1, timeout2

用流程图看更清晰:

总结

有个小 tip:从规范来看,microtask 优先于 task 执行,所以如果有需要优先执行的逻辑,放入microtask 队列会比 task 更早的被执行。

最后的最后,记住,JavaScript 是一门单线程语言,异步操作都是放到事件循环队列里面,等待主执行栈来执行的,并没有专门的异步执行线程。

以上就是本章的全部内容,更多相关教程请访问JavaScript视频教程

The above is the detailed content of Detailed explanation of JavaScript event loop mechanism. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:脚本之家. If there is any infringement, please contact admin@php.cn delete
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

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.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.