Reputation: 9407
I would like to update a greeting message at 6am, 12pm, and 6pm. I am looking for the most efficient way without polling the current time too frequently inside a loop.
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);
My immediate solution, shown above, was to poll the current time every hour. As you can imagine, there is a lot of wasted processing here to just update something 3 times in a 24 hour period. Furthermore, what if the page loads in the middle of the hour, then it will miss the update.
Upvotes: 0
Views: 131
Reputation: 40842
Your code could look something like that:
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();
The used cpu load that happens every hour is negligible.
Upvotes: 2