javascriptjqueryhtmlcounterodometer

Delay between a loop using javascript or jquery for a multiple number counter


I have been trying to create a number counter using javascript and jquery. I want 2 counters where one depends on the other. I want a counter to increment from 0-2000 with an interval of 100 milliseconds between increments. and whenever one counter reaches an multiple of 200(num=200 or num=400 or num=600...) the other counter increments by one. The result expected is a counter goin from 0-2000 and another going from 0-10 in the same amount of time.

This a code snippet I have failed to get the result with:

html code:

<span id="counter" >0</span>
<span id="counter2" >0</span>

javascript code:

function counting(){
     var cc=0;
     for(var c=0;c<2000;c++){
        if((c % 200) === 0){
         $('#counter2').text(cc+1);
        }
        else{
         setTimeout(function(){$('#counter').text(c);},100);           
        }  
     }
}

Please help me out with any javascript or jquery solution..


Solution

  • Using setInterval is better suited here. Also, you should increment cc by 1 and store it in cc itself.

    function counting() {
      var cc = 0,
        c = 1;
    
      var int = setInterval(function() {
        $('#counter').text(c);
    
        if (c % 200 === 0) {
          cc += 1;
          $('#counter2').text(cc);
        }
    
        if (c >= 2000) {
          clearInterval(int);
        }
    
        c += 1;
      }, 1);
    }
    
    counting();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <span id="counter">0</span>
    <span id="counter2">0</span>

    I've modified the interval to 1ms for this demo. You may change it as per your requirements.