user2066880
user2066880

Reputation: 5034

Animate number incrementing

I'm trying to make a simple Javascript animation that increments a number until it reaches the target number. The way I'm doing it right now doesn't work however.

Here is my code: http://jsfiddle.net/nLMem/4/

HTML

<div id="number">5</div>

JS

$(document).ready(function() {
    var target = 50;
    var number = $('#number').text();

    while(number <= target) {
        setTimeout(function() {
            $('#number').text(++number);
        }, 30);
    }
});

Upvotes: 3

Views: 24665

Answers (2)

Meloman
Meloman

Reputation: 3712

Here is a solution based on user1508519 code with increment / decrement automatically and live updating on my page after ajax search/filter :

function animateResultCount(number, target, elem) {
    if(number < target) {
        var interval = setInterval(function() {
            $(elem).text(number);
            if (number >= target) {
                clearInterval(interval);
                return;
            }
            number++;
        }, 30);
    }
    if(target < number) {
        var interval = setInterval(function() {
            $(elem).text(number);
            if (target >= number) {
                clearInterval(interval);
                return;
            }
            number--;
        }, 30);
    }
}

calling my function in ajax success :

...
success: function(response) {
    $('div#results').html(response.html);
    animateResultCount($('#rescount').html(),response.newcount,'#rescount');
}
...

Upvotes: 4

user1508519
user1508519

Reputation:

This is similar to what you want:

   var interval = setInterval(function() {
        $('#number').text(number);
        if (number >= target) clearInterval(interval);
        number++;
    }, 30);

Your while loop will cause the script execution to 'freeze' while it does its work. It doesn't poll. The other problem is that you call setTimeout potentially 50 times. You only need to call setInterval once, and clear it once you reach your target number.

Upvotes: 14

Related Questions