JavaScript event loop synchronous tasks and asynchronous tasks
This article brings you relevant knowledge about javascript. It mainly introduces the JavaScript event loop synchronous tasks and asynchronous tasks. The article provides a detailed introduction around the topic, which has certain reference value. Friends in need can refer to it.
[Related recommendations: javascript video tutorial, web front-end】
Preface
First of all, before learning about synchronization and asynchronous issues in js, you need to understand that js is single-threaded. Why does it have to be single-threaded? This depends on its usage scenario. It is mainly used to allow users to interact with the page. So assuming that js is multi-threaded, in this thread, the user clicks a button and a DOM node is added. In another thread, the user clicks the button and deletes a DOM node. Then js does not know what to listen to at this time. Whose. So what is the reason for the emergence of synchronous and asynchronous? Assuming there is no asynchronous, then when we request data from the server, it may be stuck for a long time due to poor network. At this time, because it is synchronous, the web page must wait for the data request to come back before it can continue to interact with the user. This will cause the entire web page to be very busy. It's weirdly stuck and the user experience is very bad.
Execution Stack and Task Queue
Execution Stack
Let’s not talk about what the execution stack is, let’s talk about what the stack is. The stack is like a bucket. The first thing put in must be the last thing taken out, which is what everyone often calls first in, last out.
Then the execution stack turns the content blocks in the picture into code tasks. It is definitely not clear just by talking about it, but you still have to code it. :
function fn (count) { if (count <= 0) return fn(count - 1) console.log(count) } fn(3)
This is a very simple recursive code. Here we explain it directly in the picture (actually the drawing here is not rigorous, the bottom of the stack should be the global execution context):
All tasks in js will be executed on the main thread and form an execution stack. (Please remember this!!!)
Task Queue
Then the queue and the stack are opposite, the queue is first in, first out. In fact, it is easy to understand. It is the same as our usual queues. The first person to enter the queue must come out first. Then the popular understanding of task queue is used to place callback functions for asynchronous tasks. (Please remember this too!!!)
Synchronous tasks and asynchronous tasks
Let’s start with some conceptual stuff and lay a foundation:
Synchronization tasks
Many people are confused by its semantics when understanding synchronization tasks. In fact, synchronization tasks are not executed simultaneously. It is to wait for the previous execution task to end before it can execute the next task. It is not obscure to say here, but let's write a simple code to explain:
console.log(1) console.log(2) console.log(3)
The code is very simple, it is obvious. The output result is 1, 2, 3. This is the synchronization code. Then we can summarize. The synchronization tasks are queued on the main thread, and then entered into the execution stack one by one for execution until the execution stack is empty.
Asynchronous Task
Let’s give a direct example:
console.log(1) setTimeout(() => { console.log(2) }, 1000) console.log(3)
The output of this code is different from the output of the above synchronous code. The order is 1, 3, 2. This is asynchronous code. It will not be executed in the order of execution.
Similarly, let’s summarize it in official words: Asynchronous Tasks refer to tasks that do not enter the main thread but enter the "task queue" (Event queue). Only when the "task queue" notifies the main thread that an asynchronous task can be executed will the task enter the main thread for execution . It doesn’t matter if you don’t understand it. When we talk about the event loop later, you will be enlightened.
JS execution mechanism
Let’s start with the more obscure concepts:
- 1. 同步任务由JavaScript 主线程按顺序执行。
- 2. 异步任务委托给宿主环境执行。
- 3. 异步任务完成后,对应的回调函数会被加入到任务队列中等待执行,任务队列又被分为宏任务队列和微任务队列,优先执行微任务队列,常见的微任务有new Promise().then,常见的宏任务有定时器
- 4. JavaScript 主线程的执行栈被清空后,会读取任务队列中的回调函数,次序执行。
- 5. JavaScript 主线程不断重复上面的第4 步,在执行回调函数时又会按照上面的四步去执行。
js一直从任务队列中取回调函数,然后放入主线程中执行,这是一个循环不断的过程,所以把它叫做事件循环。
这个还是要简单粗暴的来段代码会更直观一点:
const promise = new Promise((resolve, reject) => { console.log(1); setTimeout(() => { console.log("timerStart"); resolve("success"); console.log("timerEnd"); }, 0); console.log(2); }); promise.then((res) => { console.log(res); }); console.log(4);
现在我们根据上面的规则一步一步分析这段代码,如果不懂Promise也没有关系,我保证这并不影响你对事件循环的理解。现在你就把自己当成js代码的检察官,要正确把它们放在合适的“位置”
- 检察官的第一步就是判断哪些是同步代码,哪些是异步代码,OK,首先从上往下看,Promise本身是同步的,所以它应该在主线程上排队,然后继续看pomise.then是个异步任务,并且是属于微任务的,它的回调函数应该在微任务队列中(此时还不在),最后一句输出语句是同步代码,应该在主线程上排队。
- 第二步,执行主线程上的同步代码,首先有Promise排着队呢,所以先输出1,随后有个定时器,所以应该把它挂起执行,由于它没有时间延迟,所以回调函数直接被放入宏任务队列,继续执行代码,遇到打印,直接输出2。现在主线程还有其他的同步代码不?是不是还有一个输出语句,所以输出4,现在主线程上的同步代码执行完了
- 第三步读取任务队列,由于微任务队列上没有东西(Promise的状态并没有改变,不会执行promise.then()),所以读取宏任务队列上的回调函数,回调函数进入主线程执行,首先输出timerStart,然后promise状态发生改变,然后又遇到一个输出语句,输出timerEnd。现在主线程上又没有东西了,又得去看任务队列上有没有东西了。
- 第四步,由于promise状态发生改变了,所以微任务队列上有回调函数了,执行输出语句,res为success,输出success
【相关推荐:javascript视频教程、web前端】
The above is the detailed content of JavaScript event loop synchronous tasks and asynchronous tasks. 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

AI Hentai Generator
Generate AI Hentai for free.

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.

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.

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

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
