Created
March 20, 2023 17:58
-
-
Save dragon-fish/bc5a82d06c1ae8aefd4dcfac6eab5722 to your computer and use it in GitHub Desktop.
Animated number
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 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