Reputation: 482
I have the following javascript countdown timer that is supposed to reset at the same time every day. At the point in which it should stop and reset, it continues to count down into a "negative time". How can I fix this?
function ShowHour() {
var now = new Date();
var hrs = 19-now.getHours();
hourLeft = +hrs+ '';
$("#hour").html(hourLeft);
}
function ShowMin() {
var now = new Date();
var mins = 60-now.getMinutes();
timeLeft = +mins+ '';
$("#min").html(timeLeft);
}
function ShowSec() {
var now = new Date();
var secs = 60-now.getSeconds();
timeLeft = +secs+ '';
$("#sec").html(timeLeft);
}
var countdown;
function StopTime() {
clearInterval(countdown);
}
setInterval(ShowHour ,1000);
setInterval(ShowMin ,1000);
setInterval(ShowSec ,1000);
Upvotes: 2
Views: 212
Reputation: 96
Try this script:
var resetHour = 19; /* 7 pm*/
function hoursLeftUntilReset() {
var curHours = (new Date()).getHours();
var hoursLeft = 0;
if (curHours <= resetHour) {
hoursLeft = resetHour - curHours;
} else {
hoursLeft = (24 - curHours) + resetHours;
}
if (hoursLeft == 0) {
// Call reset function here
}
alert('Hours Left to reset:'+ hoursLeft);
}
Upvotes: 0
Reputation: 2690
It looks like you want to reset it every day at 7 PM, correct?
The problem is in 19-now.getHours()
. Say that the hour is 23 (11:00). This will give you -4 hours, when it should be 20.
Solving this should be fairly easy. You could subtract 42-now.getHours()
to get the number of hours until 7 PM the next day, then modulus 24 (to make sure it's in 24-hour time.)
Example:
function hoursUntil7PM(){
var now = new Date();
var hrs = (42-now.getHours())%24;
alert(hrs);
}
hoursUntil7PM();
Upvotes: 1