> 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/browser/dom/type/window/.requestanimationframe.md).

# .requestAnimationFrame()

[🔰 JS](/web/js.md) ⟩ [browser](/web/browser.md) ⟩ [DOM](/web/browser/dom.md) ⟩ [type](/web/browser/dom/type.md) ⟩ [Window](/web/browser/dom/type/window.md) ⟩ .requestAnimationFrame()

{% hint style="success" %}

* run the animation

```javascript
// ⭐️ 1. request first frame
requestAnimationFrame(animate);

// render loop
// - t1: current timestamp (in ms)
// - t0: last timestamp
function animate(t1, t0) {
  if (!t0) t0 = t1;
  // ⭐️ 2. update the animation ...
  // ...
  // ⭐️ 3. request next frame if necessary
  if (!done) requestAnimationFrame(t2 => animate(t2, t1));
}
```

* stop the animation

```javascript
let id = requestAnimationFrame(animate);
// ...
cancelAnimationFrame(id);
```

{% endhint %}

{% tabs %}
{% tab title="🧨 雷區" %}
{% hint style="danger" %}
⭐️ 注意：

<mark style="color:purple;">**requestAnimationFrame()**</mark> 的 [timestamp](https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#the_time_origin) 是從「<mark style="color:yellow;">**網頁一打開**</mark>」就開始計算，並<mark style="color:red;">**不是**</mark>從執行 <mark style="color:blue;">`requestAnimationFrame(animate)`</mark> 才開始:exclamation:
{% endhint %}
{% endtab %}

{% tab title="👥 相關" %}

* [animation](/web/browser/anim.md)
  {% endtab %}

{% tab title="💈範例" %}

* [moving cat](/web/browser/anim/ex/moving-cat.md)
* [cat in hat](/web/browser/anim/ex/cat-in-hat.md)
* [cat behind hat](/web/browser/anim/ex/cat-behind-hat.md) - updating <mark style="color:yellow;">`elem.style.transform`</mark>.
  {% endtab %}

{% tab title="📘 手冊" %}

* [Window](https://developer.mozilla.org/en-US/docs/Web/API/Window) ⟩ &#x20;
  * [.requestAnimationFrame()](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
  * [.cancelAnimationFrame()](https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelAnimationFrame)
* [time origin](https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#the_time_origin) - how the timestamps are calculated in .requestAnimationFrame().
  {% endtab %}

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

* [ ] Eloquent JS ⟩ DOM ⟩ [Positioning & Animating](https://eloquentjavascript.net/14_dom.html#h_MAsyozbjjZ)
  {% endtab %}
  {% endtabs %}
