简体   繁体   中英

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.

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>

Use document ready:

$(document).ready(function() {
   run();
});

You can reset the counter by assigning count to 0.

<input id="resetCount" type="button" />

function reset() {
    $('#count').val(0);
} 

$("#resetCount").click(function() {
   reset();
});

you can call a function in onload you can do there

like

 <script>
  run();
 </script>

The run() function will call whenever the page is loading.

Just call your run method in document ready :

$(document).ready(function() {  
  run();
}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM