Skip to content

A Promise wrapper around requestAnimationFrame

License

Notifications You must be signed in to change notification settings

Calvin-LL/delay-by-animation-frame

Repository files navigation

delay-by-animation-frame

npm License: MIT

This library exports () => new Promise((resolve) => requestAnimationFrame(resolve))

Resolves to a DOMHighResTimeStamp which is a double

Install

Install with npm:

npm install delay-by-animation-frame

Install with yarn:

yarn add delay-by-animation-frame

Example

import delayByAnimationFrame from "delay-by-animation-frame";

async function animate() {
  const element = document.getElementById("element-id");
  let start;

  while (true) {
    const timestamp = await delayByAnimationFrame();

    if (start === undefined) start = timestamp;

    const elapsed = timestamp - start;

    if (elapsed > 2000) break;

    element.style.transform =
      "translateX(" + Math.min(0.1 * elapsed, 200) + "px)";
  }
}

animate();