console
/**
* timeStamp 事件属性可返回一个时间戳。指示发生事件的日期和时间
* (timestamp - startTimestamp) / duration
* 这句 timestamp 会持续变,减去初始时间戳除以持续时间即可代替setInterval()
*/
function animateValue(obj, start, end, duration) {
let startTimestamp = null;
const step = (timestamp) => {
// console.log("timestamp",timestamp)
if (!startTimestamp) startTimestamp = timestamp;
const progress = Math.min((timestamp - startTimestamp) / duration, 1);
// console.log("progress",progress)
obj.innerHTML = Math.floor(progress * (end - start) + start);
if (progress < 1) {
window.requestAnimationFrame(step);
}
};
window.requestAnimationFrame(step);
}
const obj = document.getElementById("value");
animateValue(obj, 100, 0, 5000);
<!-- 来源 -->
<!-- https://css-tricks.com/animating-number-counters/ -->
<!-- 关于 window.requestAnimationFrame 用法 -->
<!-- https://developer.mozilla.org/zh-CN/docs/Web/API/Window/requestAnimationFrame -->
<div id="value">100</div>