Mithun Raikar Mithun Raikar - 28 days ago 4x
HTML Question

How to animate the JavaScript counter

I am counting values from 0 to 100 in JavaScript, but the whole count should take 3 seconds to reach 0 to 100.but right now its happening withing milliseconds.

how can i do that?

<span><span id="counter"> </span> of 100 files</span>

for(var i=0;i<=100;i++)
setTimeout(document.getElementById("counter").innerHTML = i, 3000);



I'm guessing you mean to go from 1 - 100 in 3 seconds, here's an example:

var i = 0;

var inv = setInterval(function() {     
    if(i < 100)
        document.getElementById("counter").innerHTML = ++i;
}, 3000 / 100);

This makes the whole incrementation take about 3 seconds. It's achieved by setting an interval that (prefix) increments global variable i and sets as innerHTML every 0.03 seconds. It then clears the interval after reaching 100. You can modify step, speed, and bounds to your liking. Here's an example on JSFiddle.