Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 974
user3658991 Avatar asked Feb 10 '23 05:02

user3658991


2 Answers

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

like image 64
James Avatar answered Feb 12 '23 19:02

James


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;
}
like image 32
alexP Avatar answered Feb 12 '23 18:02

alexP