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 ?
My advice is to avoid setTimeout/Interval when using jQuery, because this library already provides means for asynchronous function calls, for example:
This animates the counter from
0toamountin 3 seconds.http://jsfiddle.net/zQWRM/2/