引言:
事件循环不是浏览器独有的,从字面上看,“循环”可以简单地认为就是重复,比如for循环,就是重复地执行for循环体中的语句,所以事件循环,可以理解为重复地处理事件,那么下一个问题是,处理的是什么事件,事件的相关信息从哪里获取。
因为我没有用nodejs做过什么项目,所以这里我暂且只关注浏览器的事件循环,但我想就“事件循环”本身而言,原理应该是相同的,不过就具体的实现可能存在一些差异。
一道面试题
相信应该有部分小伙伴和我一样,在面试中曾遇到过类似于这种问打印结果的题目。
(async function main() {
console.log(1);
setTimeout(() => {
console.log(2);
}, 0);
setTimeout(() => {
console.log(3);
}, 100);
let p1 = new Promise((resolve, reject) => {
console.log(4);
resolve(5);
console.log(6);
});
p1.then((res) => {
console.log(res);
});
let result = await Promise.resolve(7);
console.log(result);
console.log(8);
})()
这种题目就是变相的在考察事件循环的知识。
我个人感觉事件循环这个点,也是随着Promise的出现,成为了一个常见的考点。
什么是事件循环
一提到事件循环,我想很多人会和我一样,立刻想到异步、宏任务、微任务什么的。
WIKI
先不着急,我们先看下Wiki上,对事件循环的通用性描述。
In computer science, the event loop is a programming construct or design pattern that waits for and dispatches events or messages in a program. The event loop works by making a request to some internal or external "event provider" (that generally blocks the request until an event has arrived), then calls the relevant event handler ("dispatches the event"). The event loop is also sometimes referred to as the message dispatcher, message loop, message pump, or run loop.
The event-loop may be used in conjunction with a reactor, if the event provider follows the file interface, which can be selected or 'polled' (the Unix system call, not actual polling). The event loop almost always operates asynchronously with the message originator.
When the event loop forms the central control flow construct of a program, as it often does, it may be termed the main loop or main event loop. This title is appropriate, because such an event loop is at the highest level of control within the program.
简而言之,事件循环是一种编程结构或设计模式,用于在程序中等待和
标签:11,总结,console,log,循环,事件,event,loop From: https://www.cnblogs.com/lmyy/p/17831361.html