Countdown Timer (Continued)

Last week we wrote about creating a countdown timer using JavaScript. Using only 3 files one for Html, Css and JavaScript we created a fully working countdown timer. We created a Div in the Html file that would take in a varying amount of time. Styled it to be centered and colored it white in Css. Then we created a function in JavaScript to decrement the given time once per second.

I revisited this project this week and tried to make some changes. Originally we set the function to show minutes and seconds only but for the countdown timer I want to use in OBS I need to use days and hours. To achieve the desired results some modifications to the original code would have to be made.

Originally my code started out like this.

const startingMinutes = 10 

const time = startingMinutes * 60 

function UpdateCountdown() {
const minutes = Math.floor(time/60)
const seconds = time % 60

seconds = seconds > 10 ? "0" + seconds : seconds;

countdownTimer.innerHtml = `${minutes}:${seconds}`;
time--;
}

To change to time to add days and hours to it I would have to change a few things. First I needed change the startingMinutes variable to startingDays.

const startingDays = 7;

Second, I would change the time variable to be equal to startingDays * 24 * 60 * 60. This takes the startDays number and multiplies it times the number of hours in a day, number of minutes in an hour and then the number of seconds in a minute to get the total number of seconds that we are counting down.

time = startingDays * 24 * 60 * 60;

Then I needed to update the function itself

function updateCountdown() {
  const days = Math.floor(time / 24 / 60 / 60);
  const hours = Math.floor(time / startingdays / 60 / 60);
  const minutes = Math.floor(time / startingdays / 24 / 60);
  let seconds = time % 60;

  seconds = seconds < 10 ? "0" + seconds : seconds;

  countdownTimer.innerHTML = `Days ${days}  ${hours}:${minutes}:${seconds}`;
  time--;
}

I added a variable for days and hours and set them to their appropriate measurements by. Then finally I changed the innerHTML of the coundown div to reflect the additional unites of measurment.

The above picture was the result of my work. I am going to continue working on this clock for another week and try to make it a little less static. I would like the user to be able to update the clock from their side instead of having to modify the code every time I need a different time limit. I’m really enjoying this project and look forward to giving future updates on my progress.

Leave a comment

Design a site like this with WordPress.com
Get started