Skip to content

Instantly share code, notes, and snippets.

@dgolosov
Last active May 10, 2022 06:05
Show Gist options
  • Save dgolosov/638769e12c76f96906dfac870a7544af to your computer and use it in GitHub Desktop.
Save dgolosov/638769e12c76f96906dfac870a7544af to your computer and use it in GitHub Desktop.
requestAnimationFrame usage example
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