JavaScript 数字平滑变化实现 - 代码示例与解析
数字平滑变化可以通过以下代码实现:
function smoothChange(startValue, endValue, duration, callback) {
const stepTime = 10;
const steps = duration / stepTime;
let currentValue = startValue;
const stepValue = (endValue - startValue) / steps;
const intervalId = setInterval(() => {
currentValue += stepValue;
callback(currentValue);
if (Math.abs(currentValue - endValue) < Math.abs(stepValue)) {
clearInterval(intervalId);
callback(endValue);
}
}, stepTime);
}
// Example usage
smoothChange(0, 100, 1000, (value) => {
console.log(value);
});
这个函数接受四个参数:
- 'startValue':起始值。
- 'endValue':结束值。
- 'duration':变化的总时长,单位为毫秒。
- 'callback':在每个步骤结束时调用的回调函数,传递当前的值作为参数。
函数使用 'setInterval' 来定时更新当前值,并在达到目标值时停止。我们计算出每个步骤的值,并在每个步骤结束时调用回调函数。在最后一步,我们确保当前值和目标值非常接近,以避免产生不必要的小数位。
原文地址: https://www.cveoy.top/t/topic/mkIA 著作权归作者所有。请勿转载和采集!