Creating an Automatic Countdown Timer in 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 , anniversary an wishes.An automatic countdown timer in JavaScript can be implemented using the setInterval() function, which allows you to repeatedly call a function or evaluate an expression at a specified interval (in milliseconds). Here is an example of how you might use setInterval() to create an automatic countdown timer that counts down from 60 seconds:

In this article I have created a countdown timer using simple JavaScript code and shared it with you.

Source Code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Project-1 : Countdown Timer</title>
  <link rel="stylesheet" href="css/style.css">
</head>
<body>
  <p>Countdown to</p>
  <h2 class="newyear">New Year</h2>
  <div class="counter">

    <div class="box">
      <h2 id="days">00</h2>
      <small>Days</small>
    </div>

    <div class="box">
        <h2 id="hours">00</h2>
        <small>Hours</small>
      </div>

      <div class="box">
        <h2 id="minutes">00</h2>
        <small>Minutes</small>
      </div>

      <div class="box">
        <h2 id="seconds">00</h2>
        <small>Seconds</small>
      </div>
      <!-- <div class="box">
        <h2 id="mseconds">00</h2>
        <small>MillSeconds</small>
      </div> -->

  </div>
  <script src="js/script.js"></script>
</body>
</html>

The above code is an example of an HTML document that creates a countdown timer to the New Year. It consists of the following main parts:

  1. <!DOCTYPE> and <html> tags: These tags define the document type and the beginning of the HTML document.
  2. <head> and <meta> tags: The head section contains meta information about the document, such as the character set and the viewport.
  3. <title> tag: This tag sets the title of the web page, which is displayed in the browser's title bar or tab.
  4. <link> tag: This tag is used to link an external CSS file, in this case "style.css", which is used to style the document's layout and visual elements.
  5. <body> tag: The body section contains the content of the document, such as text, images, and interactive elements.
  6. <p> and <h2> tags: These tags create paragraphs and headings that display text on the page. The text "Countdown to" is wrapped in a <p> tag and "New Year" is wrapped in an <h2> tag with class "newyear"
  7. <div> tags: These tags create a container for the countdown timer. The div with class "counter" wraps around all the other divs which are used to display the days, hours, minutes and seconds.
  8. <script> tag: This tag is used to link an external JavaScript file, in this case "script.js", which is used to create the countdown timer functionality.
  9. id attribute: The id attribute is used to specify a unique id for an HTML element. In this code, each of the <h2> elements have unique id's, days, hours, minutes and seconds, which are used to select the elements and update their values in the JavaScript file.

When this HTML file is loaded in a web browser, it will display a countdown timer to the New Year, with the days, hours, minutes, and seconds displayed in separate boxes. The layout and visual elements of the timer are defined in the linked CSS file and the countdown timer functionality is defined in the linked JavaScript file.

css/style.css

@import url('https://fonts.googleapis.com/css2?family=Inspiration&family=Poppins:wght@300;400;500;700&display=swap');

*{
margin: 0;
padding:0;
font-family: 'Poppins', sans-serif;
}


body{
  width: 100vw;
  height: 100vh;
  background: linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5)),url('../images/img.jpg');
  background-size: cover;
  background-position: center;
  color:#fff;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
p{
  font-size: 13px;
}

.newyear{
  font-family: 'Inspiration', cursive;
  font-size: 50px;
  font-weight: 400;
  margin-top: 30px;
}

.counter{
  display: flex;
  margin-top: 30px;
}

.box{
  width: 50px;
  height: 50px;
  text-align: center;
}

.box h2{
  font-size: 20px;
  font-weight: 500;
}
.box small{
  font-size: 10px;
}
@media (min-width:576px) {
  p{
    font-size: 18px;
  }
  .newyear{
    font-size: 100px;
  }
  .box{
    width: 100px;
    height: 70px;
  }

  .box h2{
    font-size: 30px;
  }
  .box small{
    font-size:15px;
  }
}

@media (min-width:768px) {
  p{
    font-size: 25px;
  }
  .newyear{
    font-size: 150px;
  }
  
  .box{
    width: 150px;
    height: 100px;
  }

  .box h2{
    font-size: 50px;
  }
  .box small{
    font-size:20px;
  }
}

The above code is a JavaScript script that creates a countdown timer to the next New Year. It consists of the following main parts:

  1. Variables: The first 4 variables, "days", "hours", "minutes" and "seconds", are used to store references to the HTML elements that display the countdown timer values using the Document Object Model (DOM) method querySelector() which is used to select the element by its id.
  2. New Year: A new variable "newYear" is defined and it's value is set to the next New Year's date and time by creating a new instance of the Date object, passing a string in the format "January 1 (current year + 1) 00:00:00"
  3. function UpdateTime(): This function updates the countdown timer values every second by calculating the difference between the current date and time and the next new year date and time.
  4. Math.floor(): The date and time values are converted into days, hours, minutes, and seconds using the Math.floor() method which returns the largest integer less than or equal to a given number.
  5. innerHTML: The values for days, hours, minutes, and seconds are updated in the HTML elements by setting the innerHTML property to the calculated values.
  6. setInterval(): This function is used to call the UpdateTime() function every 1000 milliseconds or 1 second.

js/script.js

const days=document.querySelector("#days");
const hours=document.querySelector("#hours");
const minutes=document.querySelector("#minutes");
const seconds=document.querySelector("#seconds");
// const mseconds=document.querySelector("#mseconds");

const currentYear=new Date().getFullYear();
const newYear=new Date(`January 1 ${currentYear+1} 00:00:00`);

function UpdateTime(){
  const currentDate=new Date();
  const diff=newYear-currentDate;
  const d=Math.floor(diff/1000/60/60/24);
  const h=Math.floor((diff/1000/60/60)%24);
  const m=Math.floor((diff/1000/60)%60);
  const s=Math.floor((diff/1000)%60);
  const ms=Math.floor(diff%1000);

  days.innerHTML=d<10?"0"+d:d;
  hours.innerHTML=h<10?"0"+h:h;
  minutes.innerHTML=m<10?"0"+m:m;
  seconds.innerHTML=s<10?"0"+s:s;
  // mseconds.innerHTML=ms<10?"0"+ms:ms;
}
setInterval(UpdateTime,1000);

The script works by first selecting the elements on the HTML page with the specified ids and then calculates the difference between current date and time and the next new year date and time. The difference is then converted to days, hours, minutes and seconds using mathematical operation and these values are then set to the respective elements on the HTML page. This way, the script updates the values on the HTML page every second, creating a countdown timer.

Output

Countdown_timer

Live Preview


List of Programs


JS Practical Questions & Answers


JS Practical Project