+2  A: 

JavaScript and the DOM share the same thread, so the display cannot refresh whilst script is currently executing. It has to wait until the thread becomes idle. You can only achieve what you're trying to do with a setTimeout or setInterval call, increasing each step with a timer instead of a loop.

Andy E
A: 

Not sure about the JQuery side of things, but here's a quick sample page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
    <head>
        <title>test</title>
        <script type="text/javascript">
            var t, max, i;

            function Increase(amount) {
                max = amount;
                i = parseInt(document.getElementById("count").value);
                t = setInterval("SetIncrease()", 10);
            }

            function SetIncrease() {
                document.getElementById("count").value = ++i;
                if(i == max) {
                    clearTimeout(t);
                }
            }
        </script>
    </head>
    <body>
        <input id="count" type="text" value="1"/>
        <input type="button" value="Up" onclick="Increase(100)"/>
    </body>
</html>
Graham Clark
+2  A: 

Something like this is very jQuery orientated:

jQuery.fn.extend({
  animateCount : function (from, to, time) {
    var steps = 1,
        self = this,
        counter;

    if (from - to > 0) {
      steps = -1;
    };

    from -= steps;

    function step() {
      self.text(from += steps);

      if ((steps < 0 && to >= from) || (steps > 0 && from >= to)) {
        clearInterval(counter);
      };
    };

    counter = setInterval(step, time || 100);
  }
});

Now just use:

$('#selector').animateCount(1,100);

Which will count to 1 to 100, with the number incrementing every 100 ms. The interval is an optional 3rd parameter.

Matt
Thanks. Very useful!
bosh