Count animation from number A to B

后端 未结 8 989
一个人的身影
一个人的身影 2020-11-30 22:18

I am updating a numeric value inside an element by doing intervalled ajax requests.

To make the whole thing a bit more alive,

8条回答
  •  旧巷少年郎
    2020-11-30 22:34

    Current solutions do update more often than needed. Here a frame based approach, which is accurate:

    function animateValue(obj, start, end, duration) {
      let startTimestamp = null;
      const step = (timestamp) => {
        if (!startTimestamp) startTimestamp = timestamp;
        const progress = Math.min((timestamp - startTimestamp) / duration, 1);
        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, -25, 2000);
    div {font-size: 50px;}
    100

提交回复
热议问题