In this blog you will learn on how to create countdown timer with 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, launch of website or launch of a product.
HTML
<div id="countdown"></div>
Need only just a simple HTML div for this example.
CSS
Simple CSS common styling of the page.
*{
margin:0;
padding:0;
box-sizing: border-box;
}
body{
background: #53D8FB;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
#countdown {
font-size: 32px;
font-weight: 600;
font-family: Arial;
padding: 12px 40px;
background: #fff;
letter-spacing: 1px;
box-shadow: 0px 20px 25px rgba(0,0,0,0.3);
}
Javascript
let countdate = new Date("Jan 1, 2023 00:00:00").getTime();
let x = setInterval(function() {
let current = new Date().getTime();
let distance = countdate - current;
let daysleft = Math.floor(distance / (1000 * 60 * 60 * 24));
let hoursleft = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutesleft = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
let secondsleft = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("countdown").innerHTML = daysleft + "d " + hoursleft + "h "+ minutesleft + "m " + secondsleft + "s";
if (distance < 0) {
clearInterval(x);
document.getElementById("countdown").innerHTML = "🎊 HAPPY NEW YEAR 🎊";
}
}, 1000);
Using the setInterval()
function which calls the function at specific intervals in milliseconds. The functions keeps on running indefinitely until the clearInterval()
is called (Here it is line 11). Here in the code we have running the code for at 1000ms intervals.
Countdown timer counts from a certain date to indicate the beginning(or maybe end) of the event.
Use the new Date()
constructor to get the Date object. There are multiple ways to create the Date object. Please note, the Date object is static.
Preview of Countdown timer

Here is the Github link of the code. We are open for Open-Source Contribution.
Thank you for reading the blog. 🤩
Read our other blogs from here