Search code examples
javascriptvelo

Faster Number Counter Using Only JavaScript


The setInterval() method like below takes a lot of time for larger numbers such as 7,000,000 (70 seconds)

let startNum = 0;
let endNum = 7000000;    

function countIni() {
       var handle = setInterval( ()=> {
          if (startNum <= endNum) {
             var x = startNum.toLocaleString(undefined, {
                minimumFractionDigits: 0,
                maximumFractionDigits: 0
             });
             $w('#number').text = x.toString();
             startNum++;
          } else {
             clearInterval(handle);
          }
       }, 0);
    }

Is there a way the count from 0 to 7,000,000 or higher can be performed within 2 to 3 seconds. Something like this: https://teamtrees.org/

I am using Corvid so I can only use the $w("#number").text function to set the value of the text.


Solution

  • You just have to do some calculation for a delta to increment the number. Right now the following is doing 33ms which is about 30 frames per second of animation:

    Note that there is no guarantee for the delay passed to setInterval. Even a 0 means every next event cycle for setInterval (or the next event cycle for setTimeout), and is not really "immediately".

    let startNum = 0,
      endNum = 7000000,
      nSecond = 2,
      resolutionMS = 33,
      deltaNum = (endNum - startNum) / (1000 / resolutionMS) / nSecond;
    
    function countIni() {
      var handle = setInterval(() => {
    
        var x = startNum.toLocaleString(undefined, {
          minimumFractionDigits: 0,
          maximumFractionDigits: 0
        });
        document.querySelector('#number').innerHTML = x.toString();
        
        // if already updated the endNum, stop
        if (startNum >= endNum) clearInterval(handle);
        
        startNum += deltaNum;
        startNum = Math.min(startNum, endNum);
      }, resolutionMS);
    }
    
    countIni();
    <div id="number"></div>