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