Pause setTimeout when leaving the window

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts: 97

Pause setTimeout when leaving the window

The code below sends the 30s event do Google Analytics after 30 seconds a user enters a page.

Code: Select all

setTimeout(function(){
   gtag('event', '30s');
}, 30000);
But when the user minimizes the window, the event still fires.

What I want is a way to "pause" the setTimeout when the user minimizes the page and, when he maximizes the page, the setTimeout continues counting from the moment it has stopped.
Any way to do that?

Admin
You can watch for when a tab loses focus by using the event listener 'visibilitychange'. When the visibility changes, you can use 'document.hidden' to see if the document is hidden.
When hidden, clear the existing timeout, and set the time remaining into a variable; when shown, set a setTimeout with the remaining time.
Something along the lines of:

Code: Select all

let run = false;
const fn = () => {
  gtag('event', '30s');
  run = true;
};
let timeoutId;
let runAt;
let timeLeft = 30_000;
const resume = () => {
  runAt = Date.now() + timeLeft;
  timeoutId = setTimeout(fn, timeLeft);
};
resume();

document.addEventListener('visibilitychange', () => {
  if (document.hidden) {
    timeLeft = runAt - timeLeft;
    clearTimeout(timeoutId);
  }
  else if (!run) resume();
});

Similar Topics