数字增加,兼容小程序
requestAnimationFrame 为浏览器提供的方法
export function countUp(duration, from, to, onProgress) {let value = fromconst speed = (to - from) / durationconst start = Date.now()if (typeof window === 'undefined') {let requestAnimationFrame = (callback) => {setTimeout(() => {callback(Date.now());}, 1000 / 60); // 60为大多数显示器的刷新率}}function _run() {const t = Date.now() - startif (t >= duration) {value = toonProgress(value)return}value = from + t * speedonProgress(value)requestAnimationFrame(_run)}_run()
}
使用
countUp(2000, 0, 200, (val) => {console.log(val.toFixed(0))
})