Search code examples
javascripttimemomentjscountdown

How can I prevent this daily countdown timer from resetting at midnight?


Key variables to keep in mind:

This is set to simulate 11:00 PM. var bt = "23:00";
This is set to simulate 8:00 AM. var wt = "08:00";

The desired functionality:

  • The countdown timer starts every morning at 8:00 AM.
  • It counts down until 11:00 PM, every night.
  • Then it stays at 00:00:00.
  • In the morning, at 8:00 AM, it repeats the count-down, again.
  • This should happen forever.

What is actually happening:

  • Everything is working fine, except it is starting a 24 hour countdown at midnight, until 8:00 AM.

I have tried debugging this, and I suspect the error lies in what is calculated as the distance variable, making the code think that it is comparing against the next day, but I am not sure how to remedy this.

Here is the Codepen.

and here is my JS code:

$(document).ready(function () {

    var bt = "23:00";  // 11:00 PM
    var wt = "08:00";  // 08:00 AM

    var dateNow = moment().format('MMM D, YYYY');
    placeHolderDate = dateNow + " " + bt;

    var timeNow = moment().format('HH:mm');

    var countDownDate = new Date(placeHolderDate).getTime();

    var countDownHourMin = (wt.split(":"));


// Update the count down every 1 second
    var x = setInterval(function () {


        // Get todays date and time
        var now = new Date().getTime();

        // Find the distance between now and the count down date
        var distance = countDownDate - now;

        // Time calculations for days, hours, minutes and seconds
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

        $("#countDown").val(hours + ":" + minutes + ":" + seconds);

        // If the countdown is over, write some text
        if (hours === 0 && minutes === 0 && seconds === 0) {
            //clearInterval(x);
            $("#countDown").val("00:00:00");
        }

        if (hours < 0 || minutes < 0 || seconds < 0) {
            //clearInterval(x);
            $("#countDown").val("00:00:00");
        }
        var timeNow = moment().format('HH:mm');
        //console.log('Time Now:' + timeNow);
        //console.log('Wake Time:' + wt);
        if (timeNow === wt) {
            clearInterval(x);
            restartCountdown();
        }


        //console.log(hours + ":" + minutes + ":" + seconds);

    }, 1000);


    function restartCountdown() {
        //log("restartCountdown Started!");

    var bt = "23:00";  // 11:00 PM
    var wt = "08:00";  // 08:00 AM

        var dN = (moment().add(moment.duration({d: 1})).format('MMM D, YYYY'));
        console.log('dn ' + dN);

        var placeHolderDate = dN + " " + bt;
        var countDownDate = new Date(placeHolderDate).getTime();

        var countDownHourMin = (wt.split(":"));


        // Update the count down every 1 second
        var x = setInterval(function () {

            // Get todays date and time
            var now = new Date().getTime();

            // Find the distance between now and the count down date
            var distance = countDownDate - now;

            // Time calculations for days, hours, minutes and seconds
            var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            var seconds = Math.floor((distance % (1000 * 60)) / 1000);

            $("#countDown").val(hours + ":" + minutes + ":" + seconds);

            // If the countdown is over, write some text
            if (hours === 0 && minutes === 0 && seconds === 0) {
                //clearInterval(x);
                $("#countDown").val("00:00:00");
            }

            if (hours < 0 || minutes < 0 || seconds < 0) {
                //clearInterval(x);
                $("#countDown").val("00:00:00");
            }

            //  console.log(hours + ":" + minutes + ":" + seconds);

        }, 1000);

    }
});

Solution

  • I have edited your code and created this codepen https://codepen.io/anon/pen/aabjEb?editors=0010. Please feel free to optimize the code since I have not done it. The idea was is check if time is between 8 AM and 11 PM. If yes show value else show 00:00:00. Also once the date changes, update the dates and now compute accordingly

    $(document).ready(function () {

      function countdown() {
         var bt = "23:00",  // 11:00 PM
             wt = "08:00";  // 08:00 AM
    
    
        var today = new Date(),
            dd = today.getDate(),
            mm = today.getMonth()+1,
            yyyy = today.getFullYear();
    
        var startTime = new Date(mm + '/' + dd + '/' + yyyy + ' ' + wt),
            endTime = new Date(mm + '/' + dd + '/' + yyyy + ' ' + bt);
    
        setInterval(function() {
           var now = new Date();
           var nowdd = today.getDate();
           var nowTime = now.getTime();
          if(dd !== nowdd) {
            dd = nowdd;
            var nowmm = now.getMonth() + 1,
                nowyyyy = now.getFullYear();
            startTime = new Date(dd + '/' + mm + '/' + yyyy + ' wt');
            endTime = new Date(dd + '/' + mm + '/' + yyyy + ' bt');
          }
    
          if(nowTime > startTime && nowTime < endTime) {
             // Find the distance between now and the count down date
                var distance = endTime - nowTime;
    
                // Time calculations for days, hours, minutes and seconds
                var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
                    minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)),
                    seconds = Math.floor((distance % (1000 * 60)) / 1000);
                $("#countDown").val(hours + ":" + minutes + ":" + seconds);
             } else {
               $("#countDown").val("00:00:00");
             }
        }, 1000);
      }
      countdown();
    });