Sometimes, we want to count animation from number A to B with JavaScript.
In this article, we’ll look at how to count animation from number A to B with JavaScript.
Count Animation from Number A to B with JavaScript
To count animation from number A to B with JavaScript, we can use the requestAnimationFrame method to update the number.
For instance, we can write:
const animateValue = (obj, start, end, duration) => {
let startTimestamp = null;
const step = (timestamp) => {
if (!startTimestamp) startTimestamp = timestamp;
const progress = Math.min((timestamp - startTimestamp) / duration, 1);
obj.innerHTML = Math.floor(progress * (end - start) + start);
if (progress < 1) {
window.requestAnimationFrame(step);
}
};
window.requestAnimationFrame(step);
}
const obj = document.getElementById('value');
animateValue(obj, 100, -25, 2000);
to create the animateValue function that does the animation.
And we write:
<div id="value">100</div>
to add the number display.
It takes the obj parameter that is set to the element to update.
start and end are the start and end numbers for the animation.
duration is the duration of the animation.
We start the animation by setting the startTimestamp .
Then we define the step funtion that updates the startTimestamp if it’s not defined.
Next, we calculate the progress of the animation by taking the difference between timestamp and startTimestamp , then dividing that by the duration .
Then we update the innerHTML property of obj to update the number displayed.
Then if progress is less than 1, which means the animation isn’t finished, then we call window.requestAnimationFrame with step to update the number display.
Below the step function, we call window.requestAnimationFrame to start the animation.
Finally, we get the div with ID value and call animateValue to run the animation.
Now we should see the number animate from 100 to -25.
Conclusion
To count animation from number A to B with JavaScript, we can use the requestAnimationFrame method to update the number.