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 ?
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/
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With