0

I modified the code from the following post: How to create an accurate timer in javascript?

And turned it into a countdown timer:

countdownTimer(5); // seconds

function countdownTimer(duration) {
  duration *= 1000; // convert to ms
  let interval = 1000; // ms
  let expected = Date.now() + interval;
  setTimeout(step, interval);

  function step() {
    if (duration <= 0) {
      console.log("Ended");
      return;
    }
    let dt = Date.now() - expected; // the drift (positive for overshooting)
    if (dt > interval) {
      // something really bad happened. Maybe the browser (tab) was inactive?
      // possibly special handling to avoid futile "catch up" run
    } // do what is to be done

    console.log(duration / 1000);
    expected += interval;
    duration -= 1000;

    setTimeout(step, Math.max(0, interval - dt)); // take into account drift
  }
}

And it works. However I did notice that the warning in the code does affect it:

if (dt > interval) {
  // something really bad happened. Maybe the browser (tab) was inactive?
  // possibly special handling to avoid futile "catch up" run
} // do what is to be done

And really, at times when the countdown is longer than just a few seconds, something goes off, perhaps when the PC goes to sleep, or the tab was idle for a long time, I noticed it might not stay accurate.

Is there anything to do to keep the countdown timer accurate in more cases? I need this timer to display a user with a warning that his session is about to expire, but what happens is that if the user was idle for a long time, it won't even show that popup modal because the timer went off

pileup
  • 1
  • 2
  • 18
  • 45
  • 1
    Does this answer your question? [How can I make setInterval also work when a tab is inactive in Chrome?](https://stackoverflow.com/questions/5927284/how-can-i-make-setinterval-also-work-when-a-tab-is-inactive-in-chrome) – Alexander Nenashev Jun 08 '23 at 11:06
  • https://stackoverflow.com/questions/5927284/how-can-i-make-setinterval-also-work-when-a-tab-is-inactive-in-chrome – Alexander Nenashev Jun 08 '23 at 11:06

0 Answers0