Last active
July 5, 2024 14:18
-
-
Save elkcityhazard/a1308bfb61bd1087b1179b56ab04512a to your computer and use it in GitHub Desktop.
Implement the classic counter that slows down as it gets closer to it's limit (I call it a cooldown timer)
This file contains 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
class CountUp { | |
constructor(elID = "", currentIndex = 0, limit = 100, baseInterval = 30, coolDown = 90) { | |
this.elID = elID | |
this.element = document.getElementById(elID) | |
this.currentIndex = +currentIndex | |
this.limit = +this.element.dataset['count'] | |
this.baseInterval = +baseInterval | |
this.coolDown = +coolDown | |
this.percentOf = Math.floor(this.limit * this.coolDown / 100) | |
this.initCountUp() | |
} | |
initCountUp() { | |
document.addEventListener('DOMContentLoaded', this.incrementCount.bind(this)) | |
} | |
incrementCount() { | |
if (this.currentIndex > this.limit) return null // bail out if done | |
this.element.innerText = this.currentIndex | |
this.incrementSpeed = this.currentIndex / this.limit * 100 < this.coolDown ? this.baseInterval : this.baseInterval * (this.currentIndex - this.percentOf) | |
setTimeout(() => { | |
return this.incrementCount(this.elID, this.currentIndex++, this.limit, this.baseInterval, this.coolDown) | |
}, this.incrementSpeed) | |
} | |
} | |
export { CountUp } | |
const countUp = new CountUp("postCount", 0, null, 30, 80) // null because grabbing count from a data id | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment