我想在早上 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/