Count animation from number A to B

后端 未结 8 999
一个人的身影
一个人的身影 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条回答
  •  猫巷女王i
    2020-11-30 22:25

    I used a mixture of all of these to create a function that updates a BehaviorSubject.

    function animateValue(subject, timerRef, startValue, endValue, duration){
      if (timerRef) {  clearInterval(timerRef); }
      const minInterval = 100;
      const valueRange = endValue - startValue;
      const startTime = new Date().getTime();
      const endTime = startTime + (duration * 1000);
      const interval = Math.max((endTime-startTime)/valueRange, minInterval);
    
      function run() {
        const now = new Date().getTime();
        const rangePercent = Math.min(1-((endTime-now)/(endTime-startTime)),1);
        const value = Math.round(rangePercent * valueRange+startValue);
    
        subject.next(value);
        if (rangePercent >= 1) {
          clearInterval(timerRef);
        }
      }
    
      timerRef = setInterval(run, interval);
      run();
    }
    

提交回复
热议问题