my countdown should repeat every saturday at 8pm (gmt+2), however once it hits 8pm, the countdown is stuck on EXPIRED. I don't understand why, does someone recognize the issue?
Appreciate any help and thanks in advance.
function nextSaturday() {
var d = new Date();
console.log(d.getDay());
if (d.getDay() == 7 && d.getHours() < 20){
d.setHours(20);
d.setMinutes(0);
d.setSeconds(0);
return d;
}
switch (d.getDay()) {
case 0: d.setDate(d.getDate() + 6);
break;
case 1: d.setDate(d.getDate() + 5);
break;
case 2: d.setDate(d.getDate() + 4);
break;
case 3: d.setDate(d.getDate() + 3);
break;
case 4: d.setDate(d.getDate() + 2);
break;
case 5: d.setDate(d.getDate() + 1);
break;
case 6: d.setDate(d.getDate() + 0);
break;
}
d.setHours(20);
d.setMinutes(0);
d.setSeconds(0);
return d;
}
var end = nextSaturday();
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
if (distance < 0) {
clearInterval(timer);
document.getElementById("countdown").innerHTML = "EXPIRED!";
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
document.getElementById("countdown").innerHTML = "Countdown ends in: ";
document.getElementById("countdown").innerHTML += days + " days ";
document.getElementById("countdown").innerHTML += hours + " hours ";
document.getElementById("countdown").innerHTML += minutes + " minutes and ";
document.getElementById("countdown").innerHTML += seconds + " seconds left";
}
showRemaining();
timer = setInterval(showRemaining, 1000);
You are returning from this function early.
if(d.getDay() == 7 && d.getHours() < 20) {
d.setHours(20);
d.setMinutes(0);
d.setSeconds(0);
return d; //right here you are exiting your loop at 8:00 (20 hours)
}
return d;
terminates execution of the function and returns the value of d
You have d
set to this Saturday by this point, you want it to be next Saturday, so you need to add this:
d.setDate(d.getDate() + 7);
before you return d
.
Explanation:
That if statement above is basically saying, "If it's after 8:00pm on Saturday, set d to 8:00pm on Saturday." Your code will start working again at 12:00am on Sunday when it starts resetting the date to the next Saturday, you simply forgot to increment the date if it happens to be Saturday like you do for all the other days of the week.
The code exactly as it should be:
if(d.getDay() == 7) { //note: I've also updated this line to account for changes in hours
d.setHours(20);
d.setMinutes(0);
d.setSeconds(0);
if(d.getHours() >= 20)
d.setDate(d.getDate() + 7);
return d;
}