# 1、数字变化的动画

function changeNum(config, cb = () => {}) {
  let { from, to, duration = 1000 } = config;
  if (from === to) {
    cb({
        data: to,
        done: true
      });
      return;
  }
  const step = Math.floor((to - from) / 20);
  const direction = to - from >= 0; // true 表示正向
  let start = undefined;
  cb({
    data: from,
    done: false
  });
  function callback(timestamp) {
    if (start === undefined) {
      start = timestamp;
    }
    let elapsed = timestamp - start;
    if (elapsed >= duration) {
      cb({
        data: to,
        done: true
      });
      return;
    }
    let num;
    if (direction) {
      num = Math.max(Math.floor(Math.random() * step), 1);
    } else {
      num = Math.min(Math.floor(Math.random() * step), -1);
    }
    from = from + num;
    if ((direction && from >= to) || (!direction && from <= to)) {
      from = to;
    }
    if (from === to) {
      console.log(elapsed);
      cb({
        data: from,
        done: true
      });
      return;
    }
    cb({
      data: from,
      done: false
    });
    window.requestAnimationFrame(callback);
  }
  window.requestAnimationFrame(callback);
}

用法

changeNum(
  {
    from: 0,
    to: 1000
  },
  param => {
    el.textContent = param.data.toString();
  }
);
上次更新: 4/1/2025, 9:33:10 AM