Countdown Timer with JavaScript

Countdown Timer with JavaScript

Countdown timers are a useful tool for displaying a countdown to a specific event or deadline. They can be used for things like countdown clocks for events, or to create a sense of urgency for promotions. In this tutorial, we'll show you how to create a countdown timer using JavaScript.

To get started, we'll need to create a form with a single input field where the user can enter the countdown time in seconds, and a submit button to start the countdown. We'll also need to add a DOM element to our HTML where the countdown will be displayed.



HTML


<form id="form">
  <label for="countdown">Enter countdown time (in seconds):</label><br>
  <input type="number" id="countdown"><br>
  <input type="submit" value="Start countdown">
</form> 

<div id="countdown-display"></div>

Next, we'll add some JavaScript to handle the countdown logic and display the countdown to the user.

JavaScript


const form = document.getElementById("form");
const countdownDisplay = document.getElementById("countdown-display");

form.onsubmit = function(event) {
  event.preventDefault();

  let countdown = document.getElementById("countdown").value;

  const countDownTimer = setInterval(() => {
    countdownDisplay.innerHTML = countdown;
    countdown--;

    if (countdown < 0) {
      clearInterval(countDownTimer);
      countdownDisplay.innerHTML = "Done!";
    }
  }, 1000);
}

This code will get the input from the user and start the countdown when the form is submitted. The countdown will be displayed in the div element with the ID countdown-display, and will be updated every second until it reaches 0, at which point it will display "Done!".

Finally, we can add some CSS styles to give our countdown timer a nice look and feel.

CSS


#countdown-display {
  font-size: 36px;
  font-weight: bold;
  text-align: center;
  color: #333;
}

#form {
  max-width: 400px;
  margin: 0 auto;
  text-align: center;
}

#form label {
  display: block;
  font-size: 18px;
  margin-bottom: 10px;
}

#form input[type="number"] {
  width: 100%;
  font-size: 18px;
  padding: 10px;
  border: 1px
  }

Sample : https://stackblitz.com/edit/js-yks2gi?file=index.html,style.css 

Comments