Search code examples
javascriptcountdownrestart

Reset Countdown


I found a countdown that is suitable for my web-project. I want that the countdown restarts every Friday at 9 am. Could someone give me a hint? Here is the code:

(function(){
   const days = document.getElementById("days");
   const hours = document.getElementById("hours");
   const minutes = document.getElementById("minutes");
   const seconds = document.getElementById("seconds");
   const currentDate = new Date().getFullYear();

  const concertDate = new Date(`June 19 ${currentDate} 09:00:00`);

  function updateCountdown() {
     const currentTime = new Date();
     const diff = concertDate - currentTime;

     const d = Math.floor(diff / 1000 / 60 / 60 / 24);
     const h = Math.floor(diff / 1000 / 60 / 60) % 24;
     const m = Math.floor(diff / 1000 / 60) % 60;
     const s = Math.floor(diff / 1000) % 60;

     days.innerHTML = d;
     hours.innerHTML = h < 10 ? "0" + h : h;
     minutes.innerHTML = m < 10 ? "0" + m : m;
     seconds.innerHTML = s < 10 ? "0" + s : s;
}

setInterval(updateCountdown, 1000);

})();

Solution

  • Here is how I would do it. In the countdown function, add an if statement that checks whether the diff <= 0 - if it is (countdown expired), simply add one week of time to the concertDate, and the new countdown starts.

    For this to work, firstly you have to change the concertDate declaration to let concertDate to allow it to be changed later on. And also, you need to use .getTime() for the concert that will give you the time of that date in miliseconds (this makes adding one week of time at the end possible).

    (function(){
     const days = document.getElementById("days");
     const hours = document.getElementById("hours");
     const minutes = document.getElementById("minutes");
     const seconds = document.getElementById("seconds");
     const currentDate = new Date().getFullYear();
    
     let concertDate = new Date(`June 19 ${currentDate} 09:00:00`).getTime();
    
     function updateCountdown() {
     const currentTime = new Date();
     const diff = concertDate - currentTime;
    
     const d = Math.floor(diff / 1000 / 60 / 60 / 24);
     const h = Math.floor(diff / 1000 / 60 / 60) % 24;
     const m = Math.floor(diff / 1000 / 60) % 60;
     const s = Math.floor(diff / 1000) % 60;
    
     days.innerHTML = d;
     hours.innerHTML = h < 10 ? "0" + h : h;
     minutes.innerHTML = m < 10 ? "0" + m : m;
     seconds.innerHTML = s < 10 ? "0" + s : s;
    
     if (diff <= 0) {
        concertDate = concertDate + (1000 * 3600 * 24 * 7); //add one week to concert date
        }   
      }
    
    setInterval(updateCountdown, 1000);
    
    })();
    

    Hope that helps!