Amanda White
Amanda White

Reputation: 89

setInterval timer be more slower when go another chrome tab

I build a countdown timer, so - When I stay in the countdown chrome tab, its work fine. But when I go to another tab (while the countdown) running, its made it slower.

for example when you start countdown for 30 seconds, and you go to another tab for 10 seconds, when you go back to the countdown tab it will be in 24 seconds - instead of 20 seconds (its just example its very changeable).

stopper = setTimeout(progressCountdown, 1000);

the progressCountdown function its not needed here because its work fine when I in the countdown tab.

There is some option to fix that?

Upvotes: 0

Views: 1085

Answers (1)

Freyja
Freyja

Reputation: 40794

A timeout is not guaranteed to be run after exactly the given delay. In fact, there can be a number of reasons why the delay will be longer than the one you give, for instance if your web page or CPU is overloaded with work, or if it's throttled by the browser to save power and battery (which is what many browsers do with background tabs). MDN has a list with many reasons why these things may occur.

What seems to be your actual problem, however, is that you're using the timeouts to track time itself. This will often be very inaccurate due to the above problems. What you should do instead is to use a clock to keep track of the time spent before the timeout fires:

// performance.now() is a good way of measuring durations
let atStart = performance.now();

function timeoutCallback() {
  let now = performance.now();
  
  // milliseconds is accurate now matter how long the timeout actually took
  // no matter if in foreground or in background tab
  let milliseconds = now - atStart;

  // number of seconds left
  let secondsLeft = Math.ceil(30 - milliseconds / 1000);
  console.log('Countdown: ' + secondsLeft);

  if(secondsLeft > 0)
    setTimeout(timeoutCallback, 1000);
}

setTimeout(timeoutCallback, 1000);

Upvotes: 1

Related Questions