DEV Community

Ali Abbas
Ali Abbas

Posted on

Reload page after a set interval ?

Hey Devs. I have been working on this problem since a week now and it's not even finishing. All the other parts are working except for the following situation where I want to execute a script in the browser console to reload the current page after every 5 seconds of interval.

I tried using setInterval for 5000 ms but it only works for the first time and then the javascript resets. After googling and searching on stackoverflow I improved my approach and used window object to persist the setInterval function but that didnt work too.

Is there any way to achieve this?

Top comments (3)

Collapse
 
offcorner profile image
OffCorner Developer

hey,
so you want a normal site that doesn't reload unless someone clicks a button and then it should reload every 5 seconds?
you could use localStorage to check whether to reload every 5 seconds or not. here is a small example:

<div id="counter"></div>
<button id="start-counter">start reloading after every 5 seconds</button>
<button id="stop-counter">stop reloading after every 5 seconds</button>
<script>
  let reloadTimeout = null;
  const startReloading = () =>
    (reloadTimeout = setTimeout(() => window.location.reload(), 5000));
  const counterElement = document.getElementById("counter");
  const startCounterElement = document.getElementById("start-counter");
  const stopCounterElement = document.getElementById("stop-counter");
  startCounterElement.addEventListener("click", () => {
    localStorage.reloadActive = true;
    startReloading();
  });
  stopCounterElement.addEventListener("click", () => {
    localStorage.reloadActive = false;
    clearTimeout(reloadTimeout);
  });
  let counter = 0;
  window.addEventListener("load", (event) => {
    if (localStorage.reloadActive === "true") {
      startReloading();
    }
  });
  setInterval(() => {
    counterElement.innerHTML = counter++;
  }, 1000);
</script>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
coolprofessor profile image
coolprofessor

How did you set up the setInterval?

Collapse
 
offcorner profile image
OffCorner Developer

what exactly do you mean?
if the page is loaded, we check if there is an entry in localStorage saying "reloadActive":true. if that is the case, set a timeout to reload the page after 5 seconds (and then the website loads again and checks again) => so we don't use setInterval to reload our website, it is just a timeout that reloads the website and starts again.

if the localstorage tag "reloadActive" is set to false, we only increase the counter every second.

once the start counter button is pressed, we set the flag in the localStorage and set a timeout for 5 seconds.

once the stop button is pressed, we clear the flag in localStorage and remove the timeout that would reload the page