Last active
May 10, 2022 06:05
-
-
Save dgolosov/638769e12c76f96906dfac870a7544af to your computer and use it in GitHub Desktop.
requestAnimationFrame usage example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function animate(animation: AnimationFunction, ...args: unknown[]): Promise<void> { | |
let start | |
return new Promise<void>((resolve) => { | |
function step(timestamp) { | |
start ??= timestamp | |
const isRunning = animation(timestamp - start, ...args) | |
if (isRunning) { | |
window.requestAnimationFrame(step) | |
} else { | |
resolve() | |
} | |
} | |
window.requestAnimationFrame(step) | |
}) | |
} | |
function animation(elapsed: number) { | |
const duration = 2000 | |
const from = 1000 | |
const to = 9999 | |
const p = Math.min(elapsed / duration, 1) | |
const count = Math.ceil(from + (to - from) * p) | |
console.log(count) | |
return p < 1 | |
} | |
animate(animation).then(() => console.debug('Animation completed')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment