Satinder Singh Satinder Singh - 4 months ago 27
jQuery Question

Auto incrementing a counter in JavaScript

I want to animate a counter from 0 to a given value automatically on page load. Recently I found one but it works with button click.

var amount=parseInt($('#amount').val());
var i = parseInt($('#count').val());
var tim;

function run(){
tim = setInterval(function(){
if(i>=amount){clearInterval(tim); return;}
$('#count').val(++i);
},100);
}

$('#runner').click(function(){
run();
});


SEE >> JS fiddle DEMO

Also I want to add a reset button in it which will run it again from 0 on every click.

Answer

Here is Updated Jsfiddle Demo

Html:

<input type="hidden" value="10000" id="amount"/>
<input type="text" value="0" id="count"/>
<input type="button" value="Start" id="starter"/>
<input type="button" value="Stop" id="stopper"/>
<input type="button" value="reset" id="resetter"/>

Script:

<script type="text/javascript">
  var amount=parseInt($('#amount').val());
    var i = parseInt($('#count').val());
    var tim;

    function run(){
        tim = setInterval(function(){
            if(i>=amount){clearInterval(tim); return;}
            $('#count').val(++i);
        },100);        
    }
    run();

    $('#stopper').click(function(){        
        clearInterval(tim);
    });

   $('#resetter').click(function(){    
     clearInterval(tim);    
     i=0;
     $('#count').val(i);
     run();
    });

    $('#starter').click(function(){        
      clearInterval(tim);
      run();
   });
</script>