Accurate timer with javascript

51 Views Asked by At

I'm trying to build an accurate timer with javascript. My first try was using setInterval(), and of course it was a disaster. Then I tried to use requestAnimationFrame(), with the following code:

const startTimer = () => {
    let startedTime = Date.now()
    let now
    
    const insideTimer = () => {
        now = Date.now()
        if (now - startedTime > 1000) {
            setSeconds(prev => prev - 1)
            startedTime = Date.now()
            startTimer()
        } else {
            requestAnimationFrame(() => {
                insideTimer()
            })
        }
    }

    insideTimer()
}

I was very happy with the result, but turns out that when I go to another tab the timer stops, so my happiness went away.

Now I dont know how I should implement this, I tried doing it with while loops but couldn't make it work.

And I tried using setInterval() and checking every 20ms if the time difference of the Date variables is > 1000 but it seems to work exactly like the normal setInterval (I really didn't understand why)

I still want to use Date, because I think it is the best way to do it, how would you guys do it?

0

There are 0 best solutions below