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)
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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With