Countdown Timer Using JavaScript

by | Jan 30, 2023 | Coding, JavaScript

Home » Coding » Countdown Timer Using JavaScript

Introduction of the Project

A countdown is a useful tool for creating a sense of urgency and excitement for events, promotions, and deadlines. In this tutorial, we will learn how to build a countdown timer using JavaScript. By following the steps, you will be able to create a functional and customizable countdown for your own website or application. Whether you are a beginner or an experienced developer, this tutorial will provide you with a solid understanding of how to create a countdown using JavaScript.

To make this JavaScript project, we will first set up the HTML structure for the countdown timer, including placeholders for the days, hours, minutes, and seconds. Then we will write JavaScript code to calculate the time remaining until the target date and store it in variables for each unit of time (days, hours, minutes, seconds). After that, we will write JavaScript code to update the countdown display every second, decrementing the values of the time variables. And finally, we will customize the appearance of the countdown timer using CSS.

Objectives

Following are the objectives that we want to achieve through this JavaScript project.

  • To extract the current time and calculate the remaining time from the date given as input & finally start the countdown.
  • Understanding the basics of JavaScript date and time functions.
  • Creating a dynamic and visually appealing countdown timer.
  • Implementing user input to set custom countdown dates and times.
  • Handling edge cases, such as counting down to the next hour or minute.
  • Adding additional features, such as an alert or notification when the countdown reaches zero.
  • Understanding how to integrate the countdown into a larger project or website.

Requirements

The three main languages we use to build websites are HTML, CSS, and JavaScript. JavaScript is the programming language, we use HTML to structure the site, and we use CSS to design and layout the webpage.

  • Basic knowledge of HTML and CSS.
  • A text editor (e.g. Visual Studio Code, Sublime Text).
  • A modern web browser (e.g. Google Chrome, Mozilla Firefox).
  • Access to the internet for resources and support.
  • A web development environment, such as a local server or CodePen, is optional but recommended.

Source Code

HTML Code

<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
</head>
<body>
<p id="demo">00d:00h:00m:00s</p>
<label for="fname">Enter a date in format(Jan 1, 2023):</label>
<input type="text" id="date" name="date"><br><br>
<button onclick="countDown()">START COUNTDOWN</button>
<script src="countDown.js"></script>
</body>
</html>

CSS Code

p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
body{
text-align: center;
}
label{
text-align: center;
font-size: large;
}
button{
text-align: center;
font-size: large;
}

JAVASCRIPT Code

function countDown(){
let data = document.getElementById('date').value;
var countDate = new Date(data+" 00:00:00").getTime();
var x = setInterval(function() {
var nowTime = new Date().getTime();
var dist = countDate - nowTime;
var d = Math.floor(distance / (1000 * 60 * 60 * 24));
var h = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var m = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var s = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("demo").innerHTML = d + "d " + h + "h "
+ m + "m " + s + "s ";
if (dist < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
}

Explanation of the Code

The code can be broken down into three sections. The HTML & CSS involves creating the GUI and styling it, and the other is retrieving the current time, which needs to be subtracted from the date user entered to start the countdown timer.

1. It consists of a paragraph tag that displays the timer.

2. It has an input text field and a button tag to take input data and to start the timer, respectively.

3. The CSS file is meant for styling the HTML, where the buttons and labels are provided with appropriate margin, padding, font color, and font size.

Moving to the countdown process, we will apply the following:

1. It takes the date from which the timer should start as input.

2. It extracts the current date from the Date object and subtracts both dates.

3. Finally, it displays it on the webpage, and the setInterval() method calls this method after every 1 second.

Output

Main Interface

Countdown Timer Using JavaScript

Key Points To Remember

We have successfully build a simple countdown timer using JavaScript. It takes the current time and the time to which the timer should stop & returns the time left and gets updated every second so that it appears as a countdown. So let us just summarise the flow of the project

  • HTML structure: Set up the HTML for the countdown timer, including placeholders for days, hours, minutes, and seconds.
  • JavaScript calculation: Write JavaScript to calculate the time remaining until the target date and store it in variables for each unit of time (days, hours, minutes, seconds).
  • Dynamic display: Write JavaScript to update the countdown display every second, decrementing the values of the time variables.
  • Edge cases: Handle edge cases such as counting down to the next hour or minute.
  • Customization: Customize the appearance of the countdown timer using CSS.
  • Additional features: Add features such as an alert or notification when the countdown reaches zero.
  • Testing: Test the countdown timer in multiple web browsers to ensure it is functioning correctly.
  • Interval function: Use the setInterval function in JavaScript to periodically update the countdown timer.
  • Resources: Refer to online resources, such as the Mozilla Developer Network and W3Schools, for guidance and best practices.

Here are some useful resources you can refer to for building a countdown timer:

Mozilla Developer Network’s Guide to JavaScript Dates and Times: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Dates_and_Times

W3Schools Guide to JavaScript setInterval(): https://www.w3schools.com/jsref/met_win_setinterval.asp

CodePen Collection of Countdown Timer Examples: https://codepen.io/collection/XZovGQ/

 

More JavaScript Projects>>>

You May Also Like To Create…