countdown timer in javascript

To create a countdown timer in JavaScript, you can use the setInterval method to repeatedly execute a function that updates the remaining time and displays it.

Here's an example code snippet:

index.tsx
// Set the countdown date to 10 minutes from now
const countdownDate = new Date().getTime() + 10 * 60 * 1000;

// Update the countdown every second
const timer = setInterval(function() {
  // Get the current time
  const now = new Date().getTime();

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

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

  // Display the remaining time in a HTML element
  document.getElementById("timer").innerHTML = minutes + "m " + seconds + "s ";

  // If time is up, clear the interval and display a message
  if (distance <= 0) {
    clearInterval(timer);
    document.getElementById("timer").innerHTML = "Time's up!";
  }
}, 1000);
817 chars
25 lines

In this example, we set the countdown date to 10 minutes from now using the getTime method and the 10 * 60 * 1000 value, which represents 10 minutes in milliseconds. Then, we use setInterval to execute a function every second that calculates the remaining time by subtracting the current time from the countdown date. We also calculate the minutes and seconds using the floor method and update a HTML element with the remaining time using the innerHTML property. Finally, if the remaining time is zero or negative, we clear the interval and display a message.

gistlibby LogSnag