carpenumidium carpenumidium - 5 months ago 15
jQuery Question

Live update of content inside html element according to time of day

I'm trying to update content inside an html element based on the time of day, I'm doing something similar to this: Updating div content according to time but I want the content to update without a page refresh.

code:

function schoolPeriod() {
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();

// prepend minutes with 0 if < 10
if (m < 10) {
m = "0" + m;
}

h = h.toString();
m = m.toString();

var t = h + m;

var periods = [
"school assembly",
"first period",
"second period",
];

var currentPeriod = document.querySelector('.current-period');

if (t >= 600) {
currentPeriod.innerHTML = "new school day";
}
else if (t >= 900) {
currentPeriod.innerHTML = periods[0];
}
else if (t >= 940) {
currentPeriod.innerHTML = periods[1];
}
else if (t >= 1020) {
currentPeriod.innerHTML = periods[2];
}

setTimeout(schoolPeriod, 1000);
}
schoolPeriod();


codepen: http://codepen.io/carpenumidium/pen/grRYoN?editors=1011

What am I doing wrong? Appreciate the help!

Answer

You need to reverse the order of your if/else if/else if/else if tests.

Why? Lets say t is 1020. The current if condition of t >= 600 will be true, so that block will be executed rather than any of the else ifs. (Even if the if were skipped, 1020 is also greater than 900 and greater than 940...) If testing a series of >= conditions you need to start by testing the highest possibility. (You may also want to think about adding a final else statement for when it is not yet 6:00 am.)

Also, t = h + m doesn't do what you expect, because it doesn't allow for single-digit minutes (if the time is, say, 10:03 am then h + m will be 103). Instead of converting the hours and minutes to strings, multiple the hours by 60:

var t = h * 60 + m;

(There are other things you could do to make the function shorter and more extensible, but the issues I've covered are the things stopping it working in its current form.)