Skip to content

Instantly share code, notes, and snippets.

@dragon-fish
Created March 20, 2023 17:58
Show Gist options
  • Save dragon-fish/bc5a82d06c1ae8aefd4dcfac6eab5722 to your computer and use it in GitHub Desktop.
Save dragon-fish/bc5a82d06c1ae8aefd4dcfac6eab5722 to your computer and use it in GitHub Desktop.
Animated number
function animatedNumber({
from = 0,
to = 0,
duration = 0,
onUpdate,
onFinish,
}) {
const startTime = performance.now()
;(function tick() {
const current = performance.now()
const elapsedTime = Math.min(current - startTime, duration)
const currentValue = from + (to - from) * easeOut(elapsedTime / duration)
if (elapsedTime === duration) {
onFinish?.(to)
return
}
onUpdate?.(currentValue)
requestAnimationFrame(tick)
})()
}
function easeOut(t: number) {
return 1 - Math.pow(1 - t, 5)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment