Created
September 14, 2022 07:19
-
-
Save bpinazmul18/6ba6b193e044063b689f4b1622cd65d9 to your computer and use it in GitHub Desktop.
Auto increment animated counter example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// auto increment counter | |
// select elements | |
var yearOfExperiences = document.getElementById("yearOfExperiences") | |
var dedicatedEmployees = document.getElementById("dedicatedEmployees") | |
var serviceProvides = document.getElementById("serviceProvides") | |
var largeScaleGovmentProject = document.getElementById("largeScaleGovmentProject" | |
) | |
function animate(obj, initVal, lastVal, duration) { | |
let startTime = null | |
//get the current timestamp and assign it to the currentTime variable | |
let currentTime = Date.now() | |
//pass the current timestamp to the step function | |
const step = (currentTime) => { | |
//if the start time is null, assign the current time to startTime | |
if (!startTime) { | |
startTime = currentTime | |
} | |
//calculate the value to be used in calculating the number to be displayed | |
const progress = Math.min((currentTime - startTime) / duration, 1) | |
//calculate what to be displayed using the value gotten above | |
obj.innerHTML = | |
Math.floor(progress * (lastVal - initVal) + initVal) + "+" | |
//checking to make sure the counter does not exceed the last value (lastVal) | |
if (progress < 1) { | |
window.requestAnimationFrame(step) | |
} else { | |
window.cancelAnimationFrame(window.requestAnimationFrame(step)) | |
} | |
} | |
//start animating | |
window.requestAnimationFrame(step) | |
} | |
const load = () => { | |
animate(yearOfExperiences, 0, 16, 800) | |
animate(dedicatedEmployees, 0, 1000, 800) | |
animate(serviceProvides, 0, 300, 800) | |
animate(largeScaleGovmentProject, 0, 200, 800) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment