1

hear me out. suppose a page has to be reloaded every weekday at 9:30 am. the page is opened at 9 am. so at 9:15 am the page should automatically get reloaded without any user intervention. what can be done. any help is appreciated

 function checkTime() {
        var d = new Date(); // current time
        var hours = d.getHours();
         var mins = d.getMinutes();
         if (hours >= 17 || hours <= 18) {
          setInterval(() => {
           location.reload();
             }, 5000);

                   }

                }
ness
  • 39
  • 6
  • 1
    Your approach is fine in principle, is just badly indented and wrong when it comes to the details. The first problem is `hours >= 17 || hours <= 18` because that's true for any number. You also need to put the time check inside the interval, not the other way around. –  Apr 29 '21 at 15:03
  • Like this basically: https://jsfiddle.net/qwehkv0n/ –  Apr 29 '21 at 15:11

1 Answers1

0

I think you've asked the question as per this post.

But to help you quickly, I've copied the code.

function refreshAt(hours, minutes, seconds) {
    var now = new Date();
    var 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);

    var timeout = (then.getTime() - now.getTime());
    setTimeout(function() { window.location.reload(true); }, timeout);
}

Then you can add a script tag to call the refreshAt() function.

refreshAt(15,35,0); //Will refresh the page at 3:35pm

Credits to: https://stackoverflow.com/users/26210/andrew-moore

Agent K
  • 359
  • 4
  • 17
  • If there's an existing answer (there always is), don't post your own under the new question but flag it as duplicate. –  Apr 29 '21 at 15:03
  • Thanks Chris. So should I do it now? – Agent K Apr 29 '21 at 15:04
  • While it's a duplicate I disagree with the accepted answer. Especially when it comes to greater numbers, setInterval can be unreliable. I'd actually prefer the approach OP chose: use a small interval to keep checking the time, and reload if the point in time has passed. –  Apr 29 '21 at 15:05