My requestAnimationFrame function problem from number 482

Viewed 20
  • I want to display a counting number from 0 to 2022.
  • I looked up and adapted the code from MDN and from another stack question.
  • My counter goes up to 2026 for an input of 2022, where 2022 is the text content of an HTML element.
  • I tested other inputs and found that the issue starts from the number 482... which outputs +1. Bellow that number, the counter works fine.
  • I think it might be a Math.floor problem, but cannot get it...

Thanks in advance And happy new Year :)

function countNumbers(queryID, time){
    let count = document.getElementById(queryID)
    let finalNumber = parseInt(count.textContent, 10)
    let duration = time
    let start

    const step = timeStamp => {
        if (!start) start = timeStamp

        let progress = (timeStamp - start) / duration 
        count.textContent = Math.floor(progress * finalNumber)

        if (progress < 1) requestAnimationFrame(step) 
    }

    requestAnimationFrame(step)
}
document.onload = countNumbers('count', 2000)
<p>Happy new year <span id="count">2022</span></p>

0 Answers
Related