JavaScript Timer CountDown with Seconds
This tutorial is about how to create a timer countdown with seconds in javascript. We need to get the current date using Date()
the object and calculate the days, hours, minutes, and seconds and display it. Let’s make a countdown timer program to find out how many days, hours, minutes, and seconds are left until the birth of New Year 2024.
Live preview:
HTML Steps
Create a <h1>
tag to give feedback to the user when the countdown is over. You must add an ID attribute to the <h1>
tag because we can display feedback in javascript only by using the ID value.
<h1 id="display"></h1>
To display Days, Hours, Minutes, and Seconds in a separate box in the countdown timer, you need to create 4 <p>
tags inside the <div>
tag and set an ID attribute for each separately, like:
<div>
<p id="Days"></p>
<p id="Hours"></p>
<p id="Min"></p>
<p id="Sec"></p>
</div>
So we’ve only defined the elements in HTML that need to display the countdown, and we’re going to write all the time concepts in JavaScript.
JS Steps
You need to set your target date according to the syntax below. The countdown timer works based on this targetDate ie how much time is left to reach the targetDate from our currentDate
const targetDate = new Date('YYYY-MM-DDTHH:MM:SS')
You should set your Time after the text ‘T
‘. You don’t need to mention AM and PM as hours are in 24-hour format. In the 24-hour clock system, the day is divided into 24 hours, numbered from 00:00 (midnight) to 23:59 (one minute before midnight). For example, you can enter “06” to mention the Morning 6’o clock and “18” to mention the evening 6’o clock. Here, We set the target date as “2023-12-31T23:59:59
” because we are going to find the New Year for 2024.
const targetDate = new Date('2023-12-31T23:59:59');
Next, you have to get a reference for all the HTML elements we created using the elements ID name. The Countdown should be displayed in HTML only by manipulating this reference variable.
const countdownDisplay = document.getElementById('display');
const daysElement = document.getElementById('Days');
const hoursElement = document.getElementById('Hours');
const minElement = document.getElementById('Min');
const secElement = document.getElementById('Sec');
Then we use the setInterval() function to update the countdown every second and pass another function called “updateCountdown
” and “1000
” (1 second) as an argument. It will call the updateCountdown function every 1000 milliseconds (or 1 second) until it is explicitly stopped.
const countdownInterval = setInterval(updateCountdown, 1000);
Let’s define the function “updateCountdown
“,
- First, we’ll get the current Date of the user by creating
Date
() object. - Then we’ll calculate the difference between the target date and the current date by using the
Math.floor()
function to round the floating-point number, which defautly returns milliseconds, so divide it by 1000 to convert it to seconds. - Check whether the countdown has finished or not. If the value of
remainingTime
is less than 0, then the countdown is over, so put it in the if condition. If the condition is true, remove the other elements using theremove()
function and display the feedback in the “countdownDisplay
” element. - Calculate how many Days, Hours, Minutes, and Seconds are left for New Year 2024, by following below example code.
- Finally, display the Days, Hours, Minutes, and Seconds for each element using the”
innerHTML
()” function.
function updateCountdown() {
// Get the current date and time
const currentDate = new Date();
// Calculate the remaining time in seconds
const remainingTime = Math.floor((targetDate - currentDate) / 1000);
// Check if the countdown has ended
if (remainingTime <= 0) {
clearInterval(countdownInterval);
daysElement.remove()
hoursElement.remove()
minElement.remove()
secElement.remove()
countdownDisplay.innerHTML = 'HAPPY NEW YEAR!';
return;
}
// Calculate the days, hours, minutes, and seconds
let days = Math.floor(remainingTime / (3600 * 24));
let hours = Math.floor((remainingTime % (3600 * 24)) / 3600);
let minutes = Math.floor((remainingTime % 3600) / 60);
let seconds = remainingTime % 60;
// Update the countdown element
daysElement.innerHTML = `${days} <br> Days`;
hoursElement.innerHTML = `${hours} <br> Hours`;
minElement.innerHTML = `${minutes} <br> Minutes`;
secElement.innerHTML = `${seconds} <br> Seconds`;
}
Everything, we have done in this function is run every second because we passed the function in setInterval()
.
CSS Steps
Only if you add CSS styles your Countdown Timer will look beautiful and users will like it. If you use only HTML and js without CSS it won’t look good, so use CSS for styling and design.
Full Code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<style>
*{
padding: 0;
margin: 0;
}
body{
width: 100%;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background-color: red;
}
div{
display: flex;
}
div p{
border: 1px solid black;
text-align: center;
font-size: 35px;
width: 115px;
margin-left: 5px;
padding: 10px;
border-radius: 10px;
background-color: lightblue;
}
h1{
border-radius: 10px;
background-color: lightblue;
}
</style>
<body>
<h1 id="display"></h1>
<div>
<p id="Days"></p>
<p id="Hours"></p>
<p id="Min"></p>
<p id="Sec"></p>
</div>
<script>
// Set the target date and time for the countdown
const targetDate = new Date('2023-12-31T01:59:59');
// Get the countdown container element
const countdownDisplay = document.getElementById('display');
const daysElement = document.getElementById('Days');
const hoursElement = document.getElementById('Hours');
const minElement = document.getElementById('Min');
const secElement = document.getElementById('Sec');
// Update the countdown every second
const countdownInterval = setInterval(updateCountdown, 1000);
function updateCountdown() {
// Get the current date and time
const currentDate = new Date();
// Calculate the remaining time in seconds
const remainingTime = Math.floor((targetDate - currentDate) / 1000);
// Check if the countdown has ended
if (remainingTime <= 0) {
clearInterval(countdownInterval);
daysElement.remove()
hoursElement.remove()
minElement.remove()
secElement.remove()
countdownDisplay.innerHTML = 'Countdown has Ended <br> HAPPY NEW YEAR!';
}
// Calculate the days, hours, minutes, and seconds
let days = Math.floor(remainingTime / (3600 * 24));
let hours = Math.floor((remainingTime % (3600 * 24)) / 3600);
let minutes = Math.floor((remainingTime % 3600) / 60);
let seconds = remainingTime % 60;
// Update the countdown element
daysElement.innerHTML = `${days} <br> Days`;
hoursElement.innerHTML = `${hours} <br> Hours`;
minElement.innerHTML = `${minutes} <br> Minutes`;
secElement.innerHTML = `${seconds} <br> Seconds`;
}
</script>
</body>
</html>
Conclusion
So, I hope with this article you have easily understood how to create a countdown timer in JavaScript.