How To Create A Countdown Timer Using JavaScript

 


A countdown timer is an accurate timer that can be used for a website or blog to display the count down to any special event, such as a birthday or anniversary.
Basics of a countdown timer are :

  •     Set a valid end date.
  •     Calculate the time remaining.
  •     Convert the time to a usable format.
  •     Output the clock data as a reusable object.
  •     Display the clock on the page, and stop the clock when it reaches zero.

 

<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
  text-align: center;
  font-size: 60px;
  margin-top: 0px;
}
</style>
</head>
<body>

<p id="demo"></p>

<script>
// Set the date we're counting down to
var countDownDate = new Date("Jan 13, 2022 15:37:25").getTime();

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

  // Get today's date and time
  var now = new Date().getTime();
    
  // Find the distance between now and the count down date
  var distance = countDownDate - now;
    
  // Time calculations for 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);
    
  // Output the result in an element with id="demo"
  document.getElementById("demo").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";
    
  // If the count down is over, write some text
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);
</script>

</body>
</html>

Benefits of making a countdown timer in JavaScript than using plugins

  • The code will be lightweight because it will have zero dependencies.
  • The website will perform better because there won’t be any need of loading external scripts and style sheets.
  • The user gets more control because he has built the clock to behave exactly the way he wants it to rather than trying to bend a plugin according to his will.

 

Post a Comment

1 Comments

  1. I know an organization who have private investigators for hire who can help you get into your spouse’s phones,emails remotely from your phone they can also help you with your
    * credit score
    * clearing of criminal record
    *increasing of school grades and any thing that has to do with hacking etc
    You can confirm for yourself from their email ethicalhackers009@gmail.com so you can also give your testimony
    Whatsapp No: +14106350697

    ReplyDelete