Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display auto-increment values of a counter

I wish to animate a counter from 0 to a given value.

I've tried with a for() loop, but it freezes and then only displays the end value.

// HTML

<input type="hidden" value="100000" id="amount"/>
<input type="text" value="0" id="count"/>
<input type="button" value="run" id="runner"/>​

// JS

$('#runner').click(function(){
   var amount=parseInt($('#amount').val());
   for(i=0;i<=amount;i++)
   {
      $('#count').val(i);
       setTimeout(1);
   }
});

​You can see it here : http://jsfiddle.net/P4Xy6/1/

Any idea on how I could display the values between 0 and the given value ? Or any better way to do that ?

like image 943
Valky Avatar asked Dec 16 '22 03:12

Valky


2 Answers

This should do it ..

$('#runner').click(function(){
   var amount=parseInt($('#amount').val());
   var counter = 0;
   var interval = setInterval(function(){
      $('#count').val(counter++);
      if (counter > amount){
        clearInterval(interval);
      }
   },100); // the value 100 is the time delay between increments to the counter
});

Demo at http://jsfiddle.net/gaby/rbZq3/

And a more optimized one (by caching the reference to the #count element) at http://jsfiddle.net/gaby/rbZq3/2/

like image 53
Gabriele Petrioli Avatar answered Jan 01 '23 13:01

Gabriele Petrioli


My advice is to avoid setTimeout/Interval when using jQuery, because this library already provides means for asynchronous function calls, for example:

$('#runner').click(function() {
   var amount = parseInt($('#amount').val());

   $({c: 0}).animate({c: amount}, {
        step: function(now) {
            $("#count").val(Math.round(now))
        },
        duration: 3000,
        easing: "linear"
    });
})

This animates the counter from 0 to amount in 3 seconds.

http://jsfiddle.net/zQWRM/2/

like image 42
georg Avatar answered Jan 01 '23 13:01

georg