count down clock with days hours minutes seconds in javascript

index.tsx
// set the date and time to countdown to
var countDownDate = new Date("Dec 31, 2021 23:59:59").getTime();

// update the countdown every second
var countdown = setInterval(function() {

  // get the current date and time
  var now = new Date().getTime();

  // calculate the remaining time
  var distance = countDownDate - now;

  // calculate 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 countdown
  console.log(days + "d " + hours + "h " + minutes + "m " + seconds + "s");

  // when the countdown is finished
  if (distance < 0) {
    clearInterval(countdown);
    console.log("COUNTDOWN FINISHED");
  }
}, 1000);
897 chars
28 lines

This code sets a date and time to countdown to and updates the countdown every second. It uses the setInterval function to run a function every second and calculates the remaining time using the getTime() function. It then calculates the days, hours, minutes and seconds remaining and displays them in the console. Once the countdown is finished, it clears the interval and displays "COUNTDOWN FINISHED".

gistlibby LogSnag