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
Micro task | |
---|---|
then1 | |
then2 |
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!

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.

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

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.

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 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.

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

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.

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.


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

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
A free and powerful IDE editor launched by Microsoft

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
Integrate Eclipse with SAP NetWeaver application server.

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.
