animated number counter html css

Solutions on MaxInterview for animated number counter html css by the best coders in the world

showing results for - "animated number counter html css"
Alessandra
30 Oct 2020
1function animate(obj, initVal, lastVal, duration) {
2
3    let startTime = null;
4
5    //get the current timestamp and assign it to the currentTime variable
6    let currentTime = Date.now();
7
8    //pass the current timestamp to the step function
9    const step = (currentTime ) => {
10
11        //if the start time is null, assign the current time to startTime
12        if (!startTime) {
13              startTime = currentTime ;
14        }
15
16        //calculate the value to be used in calculating the number to be displayed
17        const progress = Math.min((currentTime  - startTime) / duration, 1);
18
19        //calculate what to be displayed using the value gotten above
20        obj.innerHTML = Math.floor(progress * (lastVal - initVal) + initVal);
21
22        //checking to make sure the counter does not exceed the last value (lastVal)
23        if (progress < 1) {
24              window.requestAnimationFrame(step);
25        }
26        else{
27              window.cancelAnimationFrame(window.requestAnimationFrame(step));
28        }
29    };
30
31    //start animating
32    window.requestAnimationFrame(step);
33}
34
35let text1 = document.getElementById('0101');
36let text2 = document.getElementById('0102');
37let text3 = document.getElementById('0103');
38
39const load = () => {
40    animate(text1, 0, 907, 5000);
41    animate(text2, 0, 432, 5000);
42    animate(text3, 100, 12, 5000);
43}
44