> For the complete documentation index, see [llms.txt](https://docs.hong97.ltd/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.hong97.ltd/javascript/js/eventloop.md).

# Event Loop 事件循环

代码分同步代码和异步代码，而异步代码分为：

* 宏任务：`script`, `setTimeout`, `setInterval`，由宿主环境发起的任务
* 微任务：`Promise`, `await`，由 JS 引擎本身发起的任务

另外，还需要知道：

* `setTimeout` 属于宏任务
* `Promise` 本身是同步的立即执行函数，`Promise.then` 属于微任务
* `async` 方法执行时，遇到 `await` 会立即执行表达式，表达式之后的代码放到微任务执行
* 微任务优先级大于宏任务

## 顺序

* 先同后异
* 先微后宏

Event Loop:

![](/files/3sCewsC2UViZSPSmzleO)

```javascript
setTimeout(() => { 
    console.log('timeout callback1（）')
    Promise.resolve(3).then(
      value => { 
        console.log('Promise onResolved3()', value)
      }
    )
  }, 0)
 
  setTimeout(() => { 
    console.log('timeout callback2（）')
  }, 0)
 
  Promise.resolve(1).then(
    value => { 
      console.log('Promise onResolved1()', value)
      setTimeout(() => {
        console.log('timeout callback3（）', value)
      }, 0)
    }
  )
 
  Promise.resolve(2).then(
    value => { 
      console.log('Promise onResolved2()', value)
    }
  )
 
  // Promise onResolved1() 1
  // Promise onResolved2() 2
  // timeout callback1（）
  // Promise onResolved3() 3
  // timeout callback2（）
  // timeout callback3（） 1
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.hong97.ltd/javascript/js/eventloop.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
