Categories
JavaScript Answers

How to automatically reload a web page at a certain time with JavaScript?

Spread the love

Sometimes, we want to automatically reload a web page at a certain time with JavaScript.

In this article, we’ll look at how to automatically reload a web page at a certain time with JavaScript.

How to automatically reload a web page at a certain time with JavaScript?

To automatically reload a web page at a certain time with JavaScript, we can use some date methods and setTimeout.

For instance, we write:

const refreshAt = (hours, minutes, seconds) => {
  const now = new Date();
  const then = new Date();

  if (now.getHours() > hours ||
    (now.getHours() === hours &&
      now.getMinutes() > minutes) ||
    now.getHours() === hours &&
    now.getMinutes() === minutes &&
    now.getSeconds() >= seconds) {
    then.setDate(now.getDate() + 1);
  }
  then.setHours(hours);
  then.setMinutes(minutes);
  then.setSeconds(seconds);

  const timeout = (then.getTime() - now.getTime());
  setTimeout(() => {
    window.location.reload(true);
  }, timeout);
}
refreshAt(13, 30, 0)

to define the refreshAt function.

In it, we create the now and then dates.

Next, we check if the time given by the hours, minutes, seconds has already been passed today with

now.getHours() > hours ||
(now.getHours() === hours &&
  now.getMinutes() > minutes) ||
now.getHours() === hours &&
now.getMinutes() === minutes &&
now.getSeconds() >= seconds)

If that’s true then we call setDate to set the date to tomorrow.

Then we call setHours, setMinutes and setSeconds to set the time of then.

Next, we calculate the timeOut by subtracting the timestamps of then and now in milliseconds.

Finally, we call setTimeout with a callback that calls window.location.reload to reload the page in timeout milliseconds.

Conclusion

To automatically reload a web page at a certain time with JavaScript, we can use some date methods and setTimeout.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *