【问题标题】:refresh page at a specific time在特定时间刷新页面
【发布时间】:2021-07-22 23:18:43
【问题描述】:

听我说完。假设必须在每个工作日上午 9:30 重新加载一个页面。该页面于上午 9 点打开。所以在上午 9 点 15 分,页面应该会自动重新加载,无需任何用户干预。可以做什么。任何帮助表示赞赏

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

                   }

                }

【问题讨论】:

  • 您的方法原则上很好,只是在细节方面缩进严重且错误。第一个问题是hours &gt;= 17 || hours &lt;= 18,因为对于任何数字都是如此。您还需要将时间检查放在间隔内,而不是相反。
  • 基本上是这样的:jsfiddle.net/qwehkv0n

标签: javascript loops if-statement while-loop


【解决方案1】:

我想你已经按照post 提出了这个问题。

但为了快速帮助您,我复制了代码。

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

然后你可以添加一个脚本标签来调用refreshAt()函数。

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

致:https://stackoverflow.com/users/26210/andrew-moore

【讨论】:

  • 如果已有答案(总是有),不要在新问题下发布您自己的答案,而是将其标记为重复。
  • 谢谢克里斯。那我现在应该做吗?
  • 虽然它是重复的,但我不同意接受的答案。特别是当涉及到更大的数字时,setInterval 可能不可靠。我实际上更喜欢 OP 选择的方法:使用一个小的间隔来继续检查时间,如果时间点已经过去,则重新加载。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-27
  • 1970-01-01
  • 2012-02-05
  • 1970-01-01
  • 2018-12-06
  • 2013-12-03
相关资源
最近更新 更多