javascript - 根据一天中的时间更新 html

标签 javascript jquery

我想在早上 6 点、中午 12 点和下午 6 点更新一条问候消息。我正在寻找最有效的方法,而不会在循环内过于频繁地轮询当前时间。

setInterval(function(){
    var now = new Date();
    if(now.getHours() == 6 && now.getMinutes() == 0 && now.getSeconds() == 0){
        document.getElementById('greeting').innerHTML = "Good Morning";
    } else if (now.getHours() == 12 && now.getMinutes() == 0 && now.getSeconds() == 0){
        document.getElementById('greeting').innerHTML = "Good Afternoon";
    } else if (now.getHours() == 18 && now.getMinutes() == 0 && now.getSeconds() == 0){
        document.getElementById('greeting').innerHTML = "Good Evening";
    }   
},3600000);

如上所示,我的直接解决方案是每小时轮询一次当前时间。正如您可以想象的那样,在 24 小时内仅更新 3 次内容会造成大量处理浪费。此外,如果页面在半小时加载,就会错过更新怎么办。

最佳答案

你的代码可能看起来像这样:

function updateTime() {
  var now = new Date();

  //display the greeting message base on the hour range
  if (now.getHours() >= 6 && now.getHours() < 12) {
    document.getElementById('greeting').innerHTML = "Good Morning";
  } else if (now.getHours() > 12 && now.getHours() < 18) {
    document.getElementById('greeting').innerHTML = "Good Afternoon";
  } else if (now.getHours() >= 18 || now.getHours() < 6) {
    document.getElementById('greeting').innerHTML = "Good Evening";
  }

  //do the next check to the next full hour and 1 minute
  setTimeout(updateTime, (60 - now.getMinutes() + 1) * 60 * 1000);
}


updateTime();

每小时发生的 CPU 负载可以忽略不计。

关于javascript - 根据一天中的时间更新 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39278259/

相关文章:

javascript - 如何使用Vue从表单中获取所有数据

javascript - 如何在没有查询部分的情况下获取 JavaScript 正则表达式?

javascript - 无法使用 javascript 显示 jsf 隐藏的 panelGroup

javascript - 如何使用 Perl CGI 弹出菜单打开新页面

javascript - 自动建议脚本的 jQuery Ajax 安全性

javascript - 更改日期 onchange 或 onblur

javascript - 在父容器中控制子容器滚动条

Javascript 将参数传递给回调函数

javascript - 如何在 jQuery 中实现滚动到 div 的动画?

javascript - 如何使用数据表在表格上显示更少的文本?