9

i am trying to use the following code to increment number in a textbox

    // Animate the element's value from 0 to 1100000:
$({someValue: 0}).animate({someValue: 1100000}, {
    duration: 1000,
    step: function() { // called on every step
        // Update the element's text with value:
        $('#counterx').text(Math.floor(this.someValue+1));
    }
});

it is working with small numbers like from 0 to 100 but when it comes to large number like in the mentioned code, it is not giving the target number, it is animating to numbers like 1099933 or 1099610 or ..... and every time it changes.

so how can i make it to animate to the number i specify?

4
  • 1
    what is someValue? is this a valid css property? post you markup. May 25, 2012 at 17:21
  • .animate() is best for animating CSS properties. If you want to "animate" the text inside a div, you need to create a function that loops and changes .text() at each iteration.
    – frenchie
    May 25, 2012 at 17:25
  • it is working with small numbers like from 0 to 100 . Really ?
    – Jashwant
    May 25, 2012 at 17:26
  • No you are doing the right thing. You just need to use the complete event. May 25, 2012 at 17:27

5 Answers 5

18

I have the same issue. The reasoning is because animate function uses a mathematical formula that is time based. You don't really notice this when animating something css based because close enough in pixels is good enough. It will get close to the final value but may not always be exactly the end value. Solution is to use the complete event to set that last value.

Here is what you need to do:

function animateNumber(ele,no,stepTime){
$({someValue: 0}).animate({someValue: no}, {
        duration: stepTime,
        step: function() { // called on every step. Update the element's text with value:
            ele.text(Math.floor(this.someValue+1));
        },
        complete : function(){
            ele.text(no);
        }
});
}

animateNumber($('#counterx'),100,10000);
animateNumber($('#countery'),100,1000)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
counterx(slow): <span id=counterx>--</span>
<br/>
countery(fast): <span id=countery>--</span>

4
  • 1
    Isn't that one of the most complicated way of doing it?
    – frenchie
    May 25, 2012 at 17:29
  • Who tells you these secrets ? :O Btw I agree with @frenchie
    – Jashwant
    May 25, 2012 at 17:30
  • 1
    No. I abstracted this to its own method and I actually think it is pretty clean. Much better than using a setTimeout and handling the animation myself. May 25, 2012 at 17:30
  • man you are awsom, you just forgot a comma after the step function complete :)
    – medo ampir
    May 25, 2012 at 17:35
3

1) Javascript is a single threaded application. Timeouts and animations ONLY push the event to the end of the stack based on an ideal stacking order. A long running section of script can cause the actual firing time of that event well past the accuracy you are looking for.

2) Animation approximates how much to increment, and on larger numbers that resolution is very inaccurate.

3) jQuery only has one animation buffer. You might run into some serious rendering issues if you invoke more than one "counter" using animation. Make sure to stop the previous animation before making any adjustments that effect it.

4) Even with a timeout of 0, you can expect the real world delay of ~15. Even if that is the only "thread" you have running.

Solution:

take a snapshot of the DTG
set your interval to something within the human experience, say ~200
on each interval, check how much time has passed from the original DTG
set your text field to that delta number.
stop the interval with the original DTG + "your target number" > the new DTG
2
  • I am confused on what you are answering here? May 25, 2012 at 17:56
  • There are technical aspects of JavaScript (which jQuery uses to run its animation) that cause the innacuracy cited in this question. There are also known issues with running numerous animations at the same time (such as running a .show(1000); within the same timeframe as running an animation on that same object) that may not be well known by casual users of animation. My answer is the most accurate way of knowing how much time elapsed between intervals, given that timeouts themselves are single threaded and subject to programmatic delay. Something the solution is bandaging with "complete:"
    – C.S.
    May 25, 2012 at 19:35
3

Animate is not designed to increment a counter as text (though it may work by accident, which could change with any new version of jQuery), it's designed to animate one or more CSS properties. You should be using setInterval instead.

http://jsfiddle.net/jbabey/mKa5r/

var num = 0;

var interval = setInterval(function () {
    document.getElementById('result').innerHTML = num;
    num++;

    if (num === 100) {
        clearInterval(interval);            
    }
}, 100);​
3
  • @AmirRaminfar so you downvote a simple and effective solution and suggest a complicated one?
    – jbabey
    May 25, 2012 at 17:30
  • 1
    Yea this is not what the author is asking. You also state that animate is not designed to increment counters. But it is? It works pretty well actually. Also I don't think yours a simpler solution at all. That's just an opinion. Doing setInterval and clearInterval is more complicated in my opinion. May 25, 2012 at 17:32
  • 1
    @AmirRaminfar: No, it isn't. What it is designed to do is defined in the API docs, which requires CSS properties. Just because it happens to work, doesn't mean it's designed to work. The underlying code could change in the next release, and if this technique stops working, it would not be considered a "breaking change". That said... if OP used a valid CSS property, I don't see why it would be a problem. jsfiddle.net/czbAy/2
    – user1106925
    May 25, 2012 at 17:52
2

Here's a solution that doesn't use .animate().

DEMO: http://jsfiddle.net/czbAy/4/

It's just a linear modification; you don't get the easing options if that's what you were after.

var counterx = $('#counterx'), // cache the DOM selection! :)
    i = 0,
    n = 1100000,
    dur = 1000, // 1 second
    int = 13,
    s = Math.round(n / (dur / int));

var id = setInterval(function() {
    counterx.text(i += s);
    if (i >= n) {
        clearInterval(id);
        counterx.text(n);
    }
}, int);
0

Here is a jquery plugin to animate numbers reliably, ut uses the complete callback to set the correct final number once the animation has finished:

https://github.com/kajic/jquery-animateNumber

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.