Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

543
Views
Pure JavaScript: How to refresh page after countdown if the browser tab is active

I want to achieve the following scenario:

Set a timer of 60 seconds and start the countdown displaying the timer. After the countdown is finished, refresh (not reload) the page and restart the countdown timer and continue the process.

If the browser's tab is changed, after finishing the timer, refresh the page and pause the timer, and only when the tab is active again refresh the page and start the countdown timer again.

I have managed to achieve the first requirement like:

Result will Refresh in <span id="countdown"></span>
<script>
  if (!document.hidden) {
    function timedRefresh(e) {
      var n = setInterval((function () {
        e > 0 ? (e -= 1, document.getElementById("countdown").innerHTML = e) : (clearInterval(n), window.location.reload())
      }), 1e3)
    }
    timedRefresh(59)
  }
</script>

And is unable to achieve the second requirement. I have tried to implement the solution mentioned here: Is there a way to detect if a browser window is not currently active? But it didn't work.

How do I achieve the requirements in pure JavaScript code?

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

The following code has solved this scenario. It's a little messy, but I think is understandable. We use both window.document.hasFocus() and the focus event to create this solution. I have changed the window.location.reload() methods to just consoles simulating a function that refresh the data inside the application, since is asked to us refresh (not reload).

    function timedRefresh(intervalTime) {
        let interval = null;
        let currentTime = intervalTime;

        const updateTimer = () => {
            const countdownSpan = document.getElementById("countdown");

            if (currentTime <= 0) {
                console.log(`print refresh at ${new Date()}`); // refresh page
                if (window.document.hasFocus()) {
                    currentTime = intervalTime;
                } else {
                    clearInterval(interval);
                    interval = null;
                    currentTime = intervalTime;
                }
            }

            if (!interval) {
                countdownSpan.innerHTML = "#";
            } else {
                countdownSpan.innerHTML = currentTime;
                currentTime -= 1;
            }
        };

        interval = setInterval(updateTimer, 1000);
        window.addEventListener("focus", () => {
            if (!interval) {
                interval = setInterval(updateTimer, 1000);
            }
        });
    }

    const TIMER_SECONDS = 5;
    timedRefresh(TIMER_SECONDS);

Edit:

The answer above does not work with reloads using window.location.realod(). A code solving the issue may look like this:

  const TIMER_SECONDS = 60;

/* 
 * Update span with current time
 *  `currentTime` is an integer bigger than zero or a string '#' meaning 'timer stopped'
 */
function updateDisplayTimer(currentTime){
  const countdownSpan = document.getElementById("countdown");
  countdownSpan.innerHTML = currentTime;
}

/*
 * A timer with `loopDuration` seconds. After finished, the timer is cleared.
 *  `loopDuration` is an integer bigger than zero, representing the time duration in seconds.
 */
function timedRefresh(loopDuration) {

  let currentTime = loopDuration;
  let interval = setInterval(() => {
    if (currentTime > 0) {
      updateDisplayTimer(currentTime);
      currentTime -= 1;
    } else {
      window.location.reload(); // refresh page
    }
  }, 1000);

  window.addEventListener('load', () => {
    if(window.document.hasFocus()){
      timedRefresh(TIMER_SECONDS);
    } else {
      updateDisplayTimer("#");
      clearInterval(interval);
      interval = null;
    }
  });

  window.addEventListener('focus', () => {
    if(interval == null){
      window.location.reload(); // refresh page
    }
  });
}

// exeute main fucntion 
timedRefresh(TIMER_SECONDS);
about 4 years ago · Santiago Gelvez Report

0

Use window.document.hasFocus() to determine if the user is focused on your webpage or not.

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!