如何在特定时间重新加载页面,每天只重新加载一次 [英] How to reload a page at certain hour and only once a day

查看:114
本文介绍了如何在特定时间重新加载页面,每天只重新加载一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个每分钟运行一次的javascript函数。

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);

现在的问题是,我希望重新加载每天只发生一次。因为该函数每分钟运行一次,所以下次启动它会重新加载页面再次,如果它是在上午9点到10点之间。如何重新加载只发生一次?

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?

如果我最终创建另一个函数每小时检查。如果这2个函数在同一时间启动会发生什么?

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?

解决方案

我会存储上次刷新的日期,计算差异,并且它不到6小时(为了安全起见),您不需要刷新。

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.

这篇关于如何在特定时间重新加载页面,每天只重新加载一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆