teoh4770 / pomotama

A Pomofocus clone with React and TypeScript. For personal usage + learning purposes (not in production!).
https://pomotama.netlify.app/
MIT License
10 stars 3 forks source link

[Bug] Fix the timer issue #29

Closed teoh4770 closed 2 months ago

teoh4770 commented 2 months ago

The timer will stop after switching to different tab a few minutes or so (kinda random?)

teoh4770 commented 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)
teoh4770 commented 2 months ago

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).

teoh4770 commented 2 months ago

Will need more manual test to see if the timer issue is actually fixed, but it seems good for now