Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the Event Loop of Javascript

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to implement Javascript Event Loop". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "How to implement Javascript Event Loop"!

One or four concepts.

Javascript is single threaded

Single thread means that our js code can only be executed synchronously from top to bottom, and only one task can be executed at the same time, which will cause some tasks with long execution time or uncertain execution time to block the normal execution of other tasks. The reason why Event Loop appears is to solve this problem.

2. Task Queue

To solve the above queuing problem, there is a task queue, and the browser adds the asynchronous task to the task queue for future execution after it has the result, and other tasks are executed synchronously on the main thread.

Note here that the time to add tasks to the task queue is after asynchronous tasks have results. In fact, the task queue is the existence of asynchronous task callback function.

3. Synchronous tasks and asynchronous tasks

Synchronous tasks in Js programs refer to tasks executed in the main thread, asynchronous tasks refer to tasks entering the task queue

4. Javascript execution stack

All synchronous tasks are executed on the main thread, grouped into an execution stack. When the task on the main thread finishes executing, the task is taken out of the task queue for execution.

var name = "zhouwei";setTimeout(() => { console.log(1);}, 1000);console.log(name);

The above code is executed in the browser as follows. We understand the code of the global execution environment of the program as the code wrapped in a main function. The execution stack of this code changes as follows:

Start executing code, push main task (global code execution), when asynchronous task (setTimeout) is encountered.

The browser takes over the asynchronous task and adds the result of the asynchronous task (callback function) to the task queue after 1s.

Execution of synchronous tasks in the execution stack is completed. At this time, the task queue is empty (not yet 1s), and the execution stack is also empty.

After asynchronous tasks have results, they first enter the task queue (because there may be many asynchronous tasks).

The execution stack removes tasks from the task queue and starts executing them synchronously.

Repeat step 5.

II. Event Loop

Js execution stack continuously reads tasks from the task queue and executes the process is Event Loop

We know that the task queue stores the results of asynchronous tasks, so what are the asynchronous tasks?

1. Events

There are many events in Javascript that are asynchronous tasks. The browser takes over. When an event is triggered, the callback of the event is added to the task queue and executed when there is no task in the JS execution stack.

2. HTTP request

3. Timer

4. requestAnimationFrame

macrotask and microtask

After understanding the task queue and Event Loop, we know that the Js execution stack reads task execution from the task queue, but we are not clear about this specific project. Here we introduce the concept of macro task and micro task to help us understand Event Loop.

Asynchronous task callbacks entering the task queue are divided into macro tasks and micro tasks. The rules for Js execution stack to execute macro tasks and micro tasks are shown in the following figure.

Js执行栈首先执行一个宏任务(全局代码) -> 从任务队列中读取所有微任务执行 -> UI rendering(浏览器渲染界面) -> 从任务队列读取一个宏任务 -> 所有微任务 -> UI rendering -> …

在每一轮的Event Loop结束后(1个宏任务 + 所有微任务),浏览器开始渲染界面(如果有需要渲染的UI,否则不执行UI rendering),在UI rendering结束后,开始下一轮Event Loop。

哪些是宏任务?

setTimeout

setInterval

setImmediate (Node)

requestAnimationFrame (浏览器)

I/O (事件回调)

UI rendering (浏览器渲染)

哪些是微任务?

Promise

process.nextTick (Node)

MutationObserver (现代浏览器提供的用来检测 DOM 变化的网页接口)

setTimeout延时问题

一般来说在代码中setTimeout中回调的执行时间都是大于设置的时间。 这是因为在setTimeout指定时间到达后,虽然回调函数被添加到了任务队列,但是此时Js执行栈中可能有正在执行的任务,此回调需要等待Js执行栈的任务执行完毕后才有机会执行,这就是setTimeout延时问题。

三、实战

练习下下方代码输出结果吧:

console.log(1);setTimeout(() => { console.log(2); Promise.resolve().then(() => { console.log(3) });});new Promise(resolve => { console.log(4); setTimeout(() => { console.log(5); }); resolve(6)}).then(data => { console.log(data);})setTimeout(() => { console.log(7);})console.log(8);

用上方的我们说过的js执行机制来分析这道题:

1: 执行全局任务中的同步代码输出:

1

4

8

这里需要注意的是Promise接受的handle函数是同步任务,而then方法是异步任务,所以会直接输出4。

2: 这时的任务队列中有三个setTimeout的宏任务,和一个Promise的微任务

// 此时的宏任务是setTimeout(() => { console.log(2); Promise.resolve().then(() => { console.log(3) });});setTimeout(() => { console.log(5);});setTimeout(() => { console.log(7);})// 此时微任务是then(data => { console.log(data);})

执行一个微任务, 输出:6

3: 接着执行第一个宏任务

setTimeout(() => { console.log(2); Promise.resolve().then(() => { console.log(3) });});

输出:2

在此宏任务中,向任务 队列添加了一个微任务。此时任务队列有了新的微任务。

4:执行一个微任务,输出:3

then(() => { console.log(3)});

5: 继续按照规则执行任务, 输出: 5、7

整体输出情况是:

1、4、8、6、2、3、5、7

到此,相信大家对"Javascript的Event Loop怎么实现"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report