【问题标题】:Javascript: How Do I Refresh Page At Midnight?Javascript:如何在午夜刷新页面?
【发布时间】:2023-03-19 18:12:01
【问题描述】:

我一直试图让我的页面在午夜刷新,但我编写的代码不起作用。

这是我写的代码:

function reloadClock() {
  var reloadTime = new Date();
  var hrs = reloadTime.getHours();
  var min = reloadTime.getMinutes();
  var sec = reloadTime.getSeconds();
  
  // I tried this code, it will not work.
  if (hrs == 0 && min == 0 && sec == 0) {
    alert('this page will now reload');
    location.reload();
  }
  
  // I also tried this code, still can't get it to work.
  if (hrs == 14) { // Works as intended.
    alert(hrs);
    if (min == 31) { // Works as intended.
      alert(min);
      if (sec == 0) { // Does not work as intended.
        alert(sec);
        location.reload();
      }
    }
  }
  setTimeout(reloadClock(), 1000);
}

有人知道解决办法吗?

【问题讨论】:

  • setTimeout(reloadClock(), 1000); 也不起作用

标签: javascript clock


【解决方案1】:

检查一下

const timerefresh = setInterval(function(){
  const time_ = new Date().toLocaleString('en-GB'); // return 24 hour time format in string, explaination about en-GB you can search on wikipedia, thats bored (:
  let date = time_.split(', ')[0].split('/'); // split the time strings to get date in array [day, month, year]
  let clock = time_.split(', ')[1].split(':'); // split the time strings to get clock in array [hour, min, sec]
  countDownTime(Number(clock[0]),Number(clock[1]),Number(clock[2]));
  document.getElementById('time1').innerHTML = 'date:'+date+', clock:'+clock;
  
},1000);
function countDownTime(h,m,s){
// some match to reverse the clock
document.getElementById('time2').innerHTML = 'countdown to midnight : '+ (23-h)+':'+(59-m)+':'+(60-s);
if(h === 23 && m === 59 && s === 59){ itsMidnight(); } // call its midnight 1 sec before clock 00:00:00
}
function itsMidnight(){
// its midnight, your function here
  console.log('midnight! reload.')
  window.location.reload();
}

// code below just for testing, you can delete it
let sectomidnight = 50;
function gotoMidnight(){
  clearInterval(timerefresh);
  setInterval(function(){
    sectomidnight += 1;
    countDownTime(23,59,sectomidnight);
  },1000);
  
}
<div id="time1"></div>
<div id="time2"></div>
<button onclick="gotoMidnight();">goto 10 sec before midnight</button>

【讨论】:

  • 嘿,我只是对我的代码进行了修改。查看上次更新
  • check this 不是一个有用的描述。你应该解释你改变了什么以及为什么。原始代码有什么问题?你改变了什么,为什么这很重要?在目前的形式中,答案是有一点不同。
  • 这是非常简单的代码,我想你可以理解它。你不明白哪一部分?
  • 我理解代码。那不是问题。但是与 OP 或什至 OP 有相同问题的人可能不知道原始代码的哪一部分是问题所在,否则一开始就不会提出问题。答案不仅应该帮助被问到的人,还应该帮助任何未来的读者。
  • 我已经在我的代码中添加了一些注释。希望对您有所帮助
猜你喜欢
  • 2016-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-03
  • 1970-01-01
  • 2020-09-30
  • 1970-01-01
相关资源
最近更新 更多