1

I have code that is supposed to run in the background doing a countdown, and the count down is being shown in a modal.

When switching tabs the countdown stops, and my code on the first tab is not being executed anymore. How can I keep my code running in the background?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
badbyte
  • 83
  • 1
  • 10

1 Answers1

2

Chrome and other browsers have some restrictions on JavaScript running in an inactive tab (low priority, timeout interval must be > 1000 ms, etc., etc.). The best advice I can give you is to not rely entirely on timer (setInterval(), setTimeout()) to update your JavaScript timer.

If you would record the starting timestamp of your timer:

const currentDate = new Date();
const timerStart = currentDate.getTime(); // return date in milliseconds from 1 Jan 1970

then you'll be able to calculate the time elapsed at any time when you'll back to your tab, without relying on execution priority for idle tabs behavior across all browsers.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43