Closed teoh4770 closed 2 months ago
When a tab is inactive, many browsers reduce the frequency at which setInterval
or setTimeout
callbacks are executed (normally once per second). This throttling can cause traditional timers to be inaccurate, as they rely on consistent interval execution.
We should actually calculating the actual elapsed time
(Date.now() - lastTime.getTime()
)
rather than relying on interval execution alone, assume that 1000ms
has passed between each setInterval
call (which normally wouldn't)
By continuously adding the actual elapsed time to count, the timer stays accurate even if the browser reduces the interval execution frequency when the tab is inactive.
Codepen Example: https://codepen.io/ck0306/pen/rNEpozv
let count = 0;
let lastTime = new Date();
setInterval(() => {
count += Date.now() - lastTime.getTime();
lastTime = new Date();
document.getElementById('time').textContent = Math.floor(count / 1000);
}, 250)
We can also remove the logic away from the main thread by using web worker, which also help preventing inactive tab throttling (most of the time).
Will need more manual test to see if the timer issue is actually fixed, but it seems good for now
The timer will stop after switching to different tab a few minutes or so (kinda random?)