> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/js/async/event-loop.md).

# event loop

[JS](/web/js.md) ⟩ [async code](/web/js/async.md) ⟩ event loop

{% hint style="success" %}

{% endhint %}

{% tabs %}
{% tab title="💈範例" %}
replit ⟩ [event loop](https://replit.com/@pegasusroe/event-loop#index.js)

```javascript
const { log } = console;

// ----------
//   case 1
// ----------

try {
    setTimeout(() => {
        throw new Error("Woosh");            // ⭐ async code
    }, 2000);
} catch (_) {
    log("Caught!");                          // this will not run❗
}

// ----------
//   case 2
// ----------

Promise.resolve("Done").then(console.log);    // ⭐ async code
console.log("Me first!");

// ----------
//   case 3
// ----------

let start = Date.now();
const elapsed = () => Date.now() - start;

// 1. send a minitask to event loop (plan to run in 20 ms)
setTimeout(() => {
    log("Timeout ran at:", elapsed());        // ⭐ async code
}, 20);

// 2. fiddle around for (at least) 50 ms
while (elapsed() < 50) { }

// 3. sync code ends
log("Wasted time until:", elapsed());

// (sync code ends)
// -----------------------
// Me first!
// Wasted time until: 67

// ⭐ (async code begins)
// -----------------------
// Done
// Timeout ran at: 72

// Error: Woosh
```

{% endtab %}

{% tab title="📗 參考" %}

* Eloquent JS ⟩ Asynchronous Programming ⟩ [The Event Loop](https://eloquentjavascript.net/11_async.html#h_GXDb0+eMId)&#x20;
  {% endtab %}
  {% endtabs %}
