Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

javascript - How to reload a page at certain hour and only once a day

I have a javascript function that runs every one minute.

setInterval(function(){

  //first, check time, if it is 9 AM, reload the page
   var now = new Date();
   if (now.getHours() == 9 {
      window.refresh();
   }

  //do other stuff

},60000);

Now the problem is, I want the reload to happen only once a day. since the function runs every minutes, so next time it fires up, it will reload the page again if it is between 9AM and 10AM. How do I make the reload happen only once?

I can probably do it by creating another interval function that fires every hour and check if I should reload. but since I already have the above function that runs every minute, can I do it from there?

If I do end up with creating another function that checks every hour. What will happen if those 2 functions fire up at the exact same time?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would store the date of the last refresh, calculate the difference, and it it's less than 6 hours (to be safe) you won't need a refresh.

var lastRefresh = new Date(); // If the user just loaded the page you don't want to refresh either

setInterval(function(){

  //first, check time, if it is 9 AM, reload the page
   var now = new Date();
   if (now.getHours() == 9 && new Date() - lastRefresh > 1000 * 60 * 60 * 6) { // If it is between 9 and ten AND the last refresh was longer ago than 6 hours refresh the page.
      location.reload();
   }

  //do other stuff

},60000);

I hope this is what you meant. Note this is untested.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...