JavaScript 数字平滑变化实现 - 使用定时器和缓动函数
JavaScript 中数字平滑变化可以通过定时器和缓动函数实现。以下是一个简单的例子:
function smoothChange(target, duration) {
let current = 0;
const increment = target / (duration / 10); // 每10毫秒增加的值
const timer = setInterval(() => {
current += increment;
if (current >= target) {
clearInterval(timer);
current = target;
}
console.log(current); // 输出当前值
}, 10);
}
smoothChange(100, 1000); // 在1000毫秒内使数字平滑变化到100
在上面的例子中,我们使用了一个定时器来每隔10毫秒更新一次数字的值,同时使用缓动函数来实现平滑变化。increment 变量表示每10毫秒数字增加的值,可以根据需要调整。在定时器的回调函数中,我们每次将当前值加上 increment,如果达到了目标值,就清除定时器,并将当前值设置为目标值。在实际使用中,可以根据需要将输出当前值的语句替换为其他操作,比如将数字渲染到页面中。
原文地址: https://www.cveoy.top/t/topic/mkIJ 著作权归作者所有。请勿转载和采集!