Forced sorting of javascript event loop
js single thread
js is single-threaded, which is more conducive to user interaction and DOM operations; for a detailed explanation of processes and threads, you can click on the portal; although webworker can implement multi-threading, in essence It is also single-threaded. The threads created by webworker are controlled by the main thread and can only perform calculations;
js synchronization and asynchronous
Synchronous execution: that is, the js main thread executes tasks in sequence , if you operate webAPI/ajax and other codes, you will wait for its response and the subsequent code will not be executed, that is, the next task must wait until the previous task is completed;
Asynchronous execution: js is single-threaded and does not It has asynchronous capabilities, but the browser can; when js is executed and encounters webAPI (such as setTimeout/ajax, etc.), a value will be returned immediately, thereby not blocking the main thread, and the real asynchronous is executed by the browser, and it will be discussed after it is completed. The callback function is pushed into the message queue of the js main thread and waits for the main thread to call;
Event loop mechanism [Event-loop]
When js is executed, its main thread has an execution stack [personal habit is called Call stack] (stack) and a message queue [also called task queue or event queue] (Event-queue); when js encounters a function during execution, it will be pushed onto the stack and popped out of the stack after the function is executed, and the main thread calls Execute the stack and execute it. If it encounters webAPI, it will be executed asynchronously; when there is no task in the execution stack, the main thread will query the message queue. If the query is successful, the queried task will be pushed into the stack for execution until the execution stack is empty, and the message will be queried again. Queuing up to form a loop is the famous event loop [Event-loop]; since asynchronous execution is completed by the browser, it is easy to understand why operating dom events when the js thread is blocked will be executed sequentially after the thread is restored, [js main thread The task queue is pushed by the browser, and the js thread is blocked! == The browser thread is blocked. In other words, even if the main thread is blocked, it will not prevent the task from being pushed into the task queue]; draw a sketch;
Here is another piece of code:
// 主线程执行fn1任务 1function fn1(){ console.log("任务1执行")// 遇到webAPI立即返回 这里是undefined值 并交给浏览器对应线程处理 2 // 浏览器收到后 0 毫秒将回调函数推入消息列队; 异步执行setTimeout(function(){// 查询到一个回调任务 入栈执行 5console.log("回调1执行")// 遇到webAPI立即返回 这里是undefined值 并交给浏览器对应线程处理 6 // 浏览器收到后 500 毫秒将回调函数推入消息列队; 异步执行setTimeout(function(){// 查询到一个回调任务 入栈执行 7console.log("回调2执行") },500) },0) }// 主线程执行fn2任务 3function fn2(){console.log("任务2执行")}// 执行栈没有可执行任务 开始查询消息列队 4
Macrotasks and Microtasks
The message queue is divided into two types, namely Macrotasks[Task Queue] and Microtasks[Microtasks Queue] ];
macrotasks:
setTimeout
,setInterval
,setImmediate
, I/O, UI renderingmicrotasks:
process.nextTick
,Promises
,Object.
MutationObserver
This raises a question, which of the two should execute first? The Promise/A+ specification states:
console.log(170 Promise(89100 Promise(34562); // 1 2 3 4 5 6 7 8 9 10
The above code execution process:
js executes console 1. When setTimeout is encountered, it is changed to asynchronous execution, and when setTimeout is encountered again, it is executed asynchronously again. Then the execution encounters a promise and is pushed into the microtasks type task queue for execution. Console 2 At this point, the execution stack is empty and the message queue is started to be queried. First, query microtasks and find that there is a task that can be executed. Then the task will be pushed into the stack for execution and the corresponding print will be 3 4 5 6 [As long as is found If microtasks is not empty, it will be executed until it is empty】; Query the message queue again. At this time, the microtasks queue has no tasks to execute. Then query the macrotasks queue and find a setTimeout callback waiting to be executed. Then Push the stack and pop it out, printing 7; query the queue again. At this time, the microtasks queue still has no tasks. Then query the macrotasks queue and find a setTimeou callback waiting to be executed. When the stack is executed, it is found that the promise is pushed into microtasks. The queue is popped out of the stack, and the execution stack is empty again. Query the message queue and find that microtasks have tasks that can be executed, push them into the stack and pop them out; print the response 8 9 10; at this point the execution ends and the main thread is in a waiting state;
##
The above is the detailed content of Forced sorting of javascript event loop. 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

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.

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

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

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.

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We
