Search code examples
javascripthtmlcounter

Restart counter every week


I would like to create a counter that reset every week, I found a code that more or less works, but when It goes to 0, it appears negative.... -1d -1h -2m -5s

            <script>
            // Set the date we're counting down to
            var countDownDate = new Date("Jan 29, 2021 20:21:0").getTime();

            // 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 an the count down date
            var distance = countDownDate - now;

            // Time calculations for days, hours, minutes and seconds
            var days = Math.floor(distance / (1000 * 60 * 60 * 24));
            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);

            // Display the result in the element with id="demo"
            document.getElementById("demo").innerHTML = days + "d " + hours + "h "
            + minutes + "m " + seconds + "s ";

            // If the count down is finished, write some text
            if (distance < 0) {
                //document.getElementById("demo").innerHTML = "GAME DAY";
                if(distance < - 1000 * 60 * 60* 24){ // if its past the "game day"
                    // reset timer to next week
                    countDownDate += 1000 * 60 * 60 * 24 * 7
                }
            }
        }, 1000);
      </script>
      <span id="demo"></span>

Solution

  • Instead of hard-coding the date, you need to calculate the next date based on the current date.

    Something like this, though you'd be better of moving the magic numbers (5 and 20) into variables.

    let getNextGameDayTime = function() {
      let now = new Date();
      let dayOfTheWeek = now.getDay();
      let dayOffset = 5 - dayOfTheWeek; // Friday is the 5th day of the week
      if (dayOffset < 0 || (dayOffset === 0 && now.getHours() > 20)) {
       dayOffset += 7;
      }
      let result = new Date();
      result.setDate(result.getDate() + dayOffset);
      result.setHours(20);
      result.setMinutes(0);
      result.setSeconds(0);
      result.setMilliseconds(0);
      return result;
    }
    
    console.log(getNextGameDayTime());

    As for not displaying the message for the hour after a countdown has finished, you could use the resulting distance for this.