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.
setInterval
call but also on page load).