How to make a countdown timer in Javascript

If you need to advertise an event (like the launch of a new product or an ICO) in your web site then you need a countdown timer.

This post explains how to build one

Keep in ming that this is a very simple countdown timer made in HTML, CSS and Javascript but you can personalize it to your event by editing the CSS and HTML file.

In this guide you can:

1- Read the post if you want to know how to build it step by step or otherwise..

2- if you are in a hurry pick it from JSFiddle https://jsfiddle.net/alketcecaj/c64mjjkj/

Step 1: First prepare the HTML, note that the div where the countdown timer goes has an id called timer. Have a look at the jsfiddle code.

Step 2 Prepare the css file in particular for the timer div


#timer {
font-size: 16px;
font-family: 'Teko', sans-serif;
width: 5OOpx;
border: 1px solid rgba(255,255,255,.2);
}

Step 3 Finally the Javascript code


var countDownDate = new Date("May 31, 2017 15:37:25").getTime();

// refresh every 1 second the timer
var x = setInterval(function() {

// this will give you current date and time
var now = new Date().getTime();

// calculate how much time from now on the count down date
var distance = countDownDate - now;

// Time in 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);

// The result goes to an element with id="timer"
document.getElementById("timer").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("timer").innerHTML = "EXPIRED";
}

}, 1000);

And here is how the timer will look. It is set at "May 31, 2018 15:37:25" and the countdown timer shows the days, hours, minutes and seconds until the given date.

Schermata 2017-10-08 alle 17.20.53.png

Now you know how to build it :-)

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center