Reputation:
I currently count down/up to a target number. The small snippet of code I currently use to do this seems to produce inconsistent results. There must be a bullet proof way of doing this without writing pages of code. Any advice would be greatly appreciated.
DEMO https://jsfiddle.net/d6anjubd/
var currentNum = $('p').text();
var targetNum = 0;
$({countNum: parseInt(currentNum)}).animate({countNum: parseInt(targetNum)}, {
duration: 500,
easing:'linear',
step: function() {
$('p').text(Math.floor(this.countNum));
},
complete: function() {
console.log('finished count');
}
});
You will notice that if you press 'run' within the jsfiddle, it will not always end in the target number, in this instance 0
.
Upvotes: 1
Views: 397
Reputation: 6880
changing the line easing:'linear'
to easing:'swing'
makes this work for me.
Guessing there might be a problem with linear easing on such short intervalls as when I increase the duration of the animation (2000+) linear works to.
An added note: The amount of error between target and result also seems to vary with the size of the difference between the two numbers (the bigger X the more error: (ABS(startValue - target) = X). This makes sense as a greater distance means it needs to travel further to get to the target.
It would also be logical for the countdown to take more time to countdown when the distance between target and value is greater. ie: duration: 15 * currentNum
Increasing the allowed time to reach the target with the distance needed to travel makes the calculation work every time for me, no matter the target or number.
Upvotes: 3