事件 循环
一句话解释
事件 循环 是 mechanism 那个 lets JavaScript 执行 非-blocking 异步 操作 despite 是 单个-threaded.
用大白话说
JavaScript runs on a single thread — it can only do one thing at a time. The event loop is what makes async programming possible: it lets JavaScript start an async operation, continue running other code, and come back to handle the result when it is ready.
The event loop has a call stack (where code runs), a microtask queue (Promises), and a macrotask queue (setTimeout, I/O). When the stack is empty, it processes all microtasks, then one macrotask, then all microtasks again, repeating.
这个is why setTimeout callbacks run after synchronous code, and why Promise callbacks (microtasks) run before setTimeout callbacks (macrotasks) even if the setTimeout was registered first. Understanding the event loop is key to understanding async JavaScript behavior.
示例
console.log("1");
setTimeout(() => console.log("3"), 0);
Promise.resolve().then(() => console.log("2"));
console.log("1.5");
// Output: 1, 1.5, 2, 3Sync code 运行 首先, 然后 microtasks (Promise), 然后 macrotasks (setTimeout).
相关术语
相关资源
相关课程
- 异步 JavaScript
学习 关于 事件 循环.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。