user3658991
user3658991

Reputation: 95

jQuery animate() doesn't finish animating

I have a problem where the animate() function of jQuery doesn't finish animating my number counting animation. The animation is simply supposed to count from 0 to 5000 but when refreshed it sometimes it ends on 4999, other times at 4989 etc.

It works 80% of the time correctly, but 20% of the time when you refresh the page the animation ends on a different number. What am I doing wrong?

http://jsbin.com/dobajepoti/2/ (keep refreshing the page to see it)

Upvotes: 4

Views: 792

Answers (3)

alexP
alexP

Reputation: 3765

Try it without jQuery:

var count = 0;
var counter = setInterval(countUp, 1);
var output = document.querySelector("[data-value]");
var max = output.getAttribute("data-value");

function countUp() {
    count = count + 25;
    if (count > max) {
        clearInterval(counter);
        return;
    }
    output.innerHTML = count;
}

Upvotes: 2

James
James

Reputation: 111900

The step() function is not guaranteed to be called on every intermediary value, but rather every step of the animation (which may be defined by a timeout or by requesting the next animation frame). And so, the final value of 5,000 will not always constitute an animation step.

To make sure that it does, you could assign your per-step function to the done callback:

$(thing).animate({
  // ...
  step: myStepFunction,
  done: myStepFunction
});

E.g. http://output.jsbin.com/fagicunuye

Upvotes: 6

ImreNagy
ImreNagy

Reputation: 511

The problem is that you animate for 1000 ms. Depending on the cpu it can be that it can not calculate 5000 times in that time. You can animate it for a longer time and use stop() to stop the animation when your condition is met.

Upvotes: 0

Related Questions