count down clock in javascript

To create a countdown clock in JavaScript, you can use the setInterval() method to update the clock every second. Here's an example:

index.tsx
// Set the date you're counting down to
const countDownDate = new Date("Sep 30, 2021 23:59:59").getTime();

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

  // Get the current time
  const now = new Date().getTime();

  // Calculate the remaining time
  const distance = countDownDate - now;

  // Calculate days, hours, minutes, and seconds
  const days = Math.floor(distance / (1000 * 60 * 60 * 24));
  const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Display the remaining time in a DIV element
  document.getElementById("countdown").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";

  // If the countdown is finished, display a message
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("countdown").innerHTML = "EXPIRED";
  }
}, 1000);
994 chars
29 lines

In this example, we set the countDownDate variable to the date and time we're counting down to. Then, we create a setInterval() function that updates every second. Inside this function, we calculate the remaining time by subtracting the current time from the countdown date. We then calculate the days, hours, minutes, and seconds remaining and display them in a DIV element using the innerHTML property. Finally, if the countdown is finished, we clear the interval and display a message.

gistlibby LogSnag