RUA!
Avatar

DefectingCat/incraseNumber.ts

Last active: a year ago

incraseNumber js javascript animation

incraseNumber.ts
/**
 * 按间隔更新数字,数字增长的动画。
 *
 * @param start 动画开始的值
 * @param end 动画最后结束的值
 * @param updateFn 更新值状态的方法
 * @param duration 动画总时长
 * @param setpDuration 每次更新的间隔
 * @param precision 数字精度
 *
 * 数字精度只会影响在动画时显示的值,不会影响最终值
 */
export function incraseNumber(
  start = 0,
  end: number,
  updateFn: (state: number) => void,
  duration = 500,
  setpDuration = 25,
  precision = 0
) {
  const times = duration / setpDuration;
  const step = end / times;

  updateFn(start);
  let count = 0;
  const update = () => {
    if (start < end) {
      start += step;
      updateFn(parseFloat(start.toFixed(precision)));
    } else if (start > end) {
      updateFn(end);
      clearInterval(count);
    } else {
      clearInterval(count);
    }
  };

  setTimeout(() => {
    /** @ts-ignore */
    count = setInterval(update, 25);
  }, 0);
}