search
HomeWeb Front-endJS TutorialJavaScript 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.

JavaScript event loop synchronous tasks and asynchronous tasks

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

JavaScript event loop synchronous tasks and asynchronous tasks

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):

JavaScript event loop synchronous tasks and asynchronous tasks

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!

Statement
This article is reproduced at:脚本之家. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

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 vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

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.