Home >Web Front-end >JS Tutorial >JavaScript event loop synchronous tasks and asynchronous tasks

JavaScript event loop synchronous tasks and asynchronous tasks

WBOY
WBOYforward
2022-09-01 14:52:321870browse

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:jb51.net. If there is any infringement, please contact admin@php.cn delete