1

I have a create-react-app that has a setInterval that runs a tick() function every 1000 millisecond. The tick() function decrements the sessionTime state by one. It works perfectly fine when the browser tab is in the foreground but it loses count in the background (not counting after a certain period). How do I allow it to continue running? Is this even the right approach to a timer in React?

TQL
  • 33
  • 1
  • 4
  • Looks like this may be a duplicate of: https://stackoverflow.com/questions/15871942/how-do-browsers-pause-change-javascript-when-tab-or-window-is-not-active – Devan Buggay Jan 12 '18 at 05:14
  • @pwnmonkey they discuss how setInterval is rounded up to 1000 milliseconds, but mine is already at 1000 milliseconds – TQL Jan 12 '18 at 05:25

1 Answers1

3

You might be running out of your time budget?

Anyway, a more reliable way is not to rely on the interval being a specific time; check current new Date() every time you execute your tick, calculate how much time has passed since last tick or since a certain remembered start time (or remaining to certain target time), and act accordingly.

For example, if you want a session to expire in 30 minutes,

let now = new Date();
const second = 1000;
const minute = 30 * second;
let expiryTime = new Date(now.getTime() + 30 * minute);

and then in your tick just check whether new Date() > expiryTime. This way, it does not matter how often your tick routine runs.

Amadan
  • 191,408
  • 23
  • 240
  • 301