ditto ditto - 7 months ago 10
Javascript Question

Setting the exact duration for incrementing to another number

I've made a function that increments one number to another. This works however my duration logic doesn't.

The third parameter in

.animateNumber()
is duration, and I want this to be the time spent incrementing to the new number.

So if the duration is set at 500, then it'll take 500 milliseconds incrementing from 10 (start) - 500 (end), and this would be the same for any starting and ending values.

http://jsbin.com/kepibetuxu/edit?html,js,console,output



HTMLElement.prototype.animateNumber = function(start, end, duration) {

this.style.opacity = 0.5;

var self = this,
range = end - start,
current = start,
increment = end > start? 1 : -1,
stepTime = duration / range,
timer = setInterval(function() {
current += increment;
self.innerHTML = current;
if (current == end) {
self.style.opacity = 1;
clearInterval(timer);
}
}, stepTime);


console.log(range);
console.log(stepTime);


};

document.querySelector('.value').animateNumber(400, 500, 20);
document.querySelector('.value1').animateNumber(0, 500, 20);

<div class="value">0</div>
<div class="value1">0</div>





How may I fix my stepTime logic to do this?

Answer

I would just request new frames, and update the number to the approapriate fraction at that time:

function animateNumber(el, start, end, duration) {
  var startTime = performance.now();
  (function func() {
    var factor = Math.min(1, (performance.now() - startTime) / duration);
    el.textContent = (start + (end-start) * factor).toFixed(0);
    el.style.opacity = factor;
    if(factor < 1) requestAnimationFrame(func);
  })();
}
animateNumber(document.querySelector('.value1'), 400, 500, 2000);
animateNumber(document.querySelector('.value2'),   0, 500, 2000);
<div class="value1">0</div>
<div class="value2">0</div>