Search code examples
javascriptresetcountdown

Stop countdown and display message daily


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?

----- JSFiddle Link -----

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);

Solution

  • 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();