Search code examples
javascriptloopswhile-loopdelayincrement

Div value increment javascript


I am trying to make a div with an animated value increasing up to it's final value. Here's an example from themeforest: http://demo.themesvision.com/drupal/evolve/ (Happy customer, projects completed, etc)

I've tried lots of different code lines with no success. I was able to do the increment, but can't figure how to make a delay each time there's an increment. I've tried setTimeout() and setInterval().

Here's my code so far:

$(document).ready(function(){
    test();

    function test(){
        var i = 0;
        while ( i <= 100 ) {
            $("#test").text(i);
            i++;
        }
    }
});

Thank in advance!


Solution

  • You need something like:

    $(document).ready(function(){
        var i = 0;
    
        test();
    
        function test(){
            $("#test").text(i++);
            if(i < 100) {
                setTimeout(test, 500);
            }
        }
    });