Build a Countdown Timer in Just 18 Lines of JavaScript

Spread the love

Sometimes, you’re going to need to build a JavaScript countdown clock. You may have an event, a sale, a promotion, or a game. You can build a clock in raw JavaScript rather than reaching for the nearest plugin. While there are many great clock plugins, here are the benefits you’ll get from using raw JavaScript:

Your code will be lightweight because it will have zero dependencies.
Your website will perform better. You won’t need to load external scripts and stylesheets.
You’ll have more control. You will have built the clock to behave exactly the way you want it to (rather than trying to bend a plugin to your will).

So, without further ado, here’s how to make your own countdown clock in a mere 18 lines of JavaScript.
For in-depth JavaScript knowledge, read our book, JavaScript: Novice to Ninja, 2nd Edition.
Basic Clock: Count down to a Specific Date or Time
Here’s a quick outline of the steps involved in creating a basic clock:

Set a valid end date.
Calculate the time remaining.
Convert the time to a usable format.
Output the clock data as a reusable object.
Display the clock on the page, and stop the clock when it reaches zero.

Set a Valid End Date
First, you’ll need to set a valid end date. This should be a string in any of the formats understood by JavaScript’s Date.parse() method. For example:
The ISO 8601 format:
const deadline = ‘2015-12-31′;

The short format:
const deadline = ’31/12/2015’;

Or, the long format:
const deadline = ‘December 31 2015’;

Each of these formats allows you to specify an exact time and a time zone (or an offset from UTC in the case of ISO dates). For example:
const deadline = ‘December 31 2015 23:59:59 GMT+0200’;

You can read more about date formatting in JavaScript in this article.
Calculate the Time Remaining
The next step is to calculate the time remaining. We need to write a function that takes a string representing a given end time (as outlined above). We then calculate the difference between that time and the current time. Here’s what that looks like:
function getTimeRemaining(endtime){
const total = Date.parse(endtime) – Date.parse(new Date());
const seconds = Math.floor( (total/1000) % 60 );
const minutes = Math.floor( (total/1000/60) % 60 );
const hours = Math.floor( (total/(1000*60*60)) % 24 );
const days = Math.floor( total/(1000*60*60*24) );

return {

First, we’re creating a variable total, to hold the remaining time until the deadline. The Date.parse() function converts a time string into a value in milliseconds. This allows us to subtract two times from each other and get the amount of time in between.
const total = Date.parse(endtime) – Date.parse(new Date());

Convert the Time to a Usable Format
Now we want to convert the milliseconds to days, hours, minutes, and seconds. Let’s use seconds as an example:
const seconds = Math.floor( (t/1000) % 60 );

Let’s break down what’s going on here.

Divide milliseconds by 1000 to convert to seconds: (t/1000)
Divide the total seconds by 60 and grab the remainder. You don’t want all of the seconds, just those remaining after the minutes have been counted: (t/1000) % 60
Round this down to the nearest whole number. This is because you want complete seconds, not fractions of seconds: Math.floor( (t/1000) % 60 )

Repeat this logic to convert the milliseconds to minutes, hours, and days.
Output the Clock Data as a Reusable Object
With the days, hours, minutes, and seconds prepared, we’re now ready to return the data as a reusable object:
return {

This object allows you to call your function and get any of the calculated values. Here’s an example of how you’d get the remaining minutes:

Convenient, right?
Display the Clock and Stop It When It Reaches Zero
Now that we have a function that spits out the days, hours, minutes, and seconds remaining, we can build our clock. First we’ll create the following HTML element to hold our clock:
<div id=”clockdiv”></div>

Then we’ll write a function that outputs the clock data inside our new div:
function initializeClock(id, endtime) {
const clock = document.getElementById(id);
const timeinterval = setInterval(() => {
const t = getTimeRemaining(endtime);
clock.innerHTML = ‘days: ‘ + t.days + ‘<br>’ +
‘hours: ‘+ t.hours + ‘<br>’ +
‘minutes: ‘ + t.minutes + ‘<br>’ +
‘seconds: ‘ + t.seconds;
if ( <= 0) {

This function takes two parameters. These are the id of the element that contains our clock, and the countdown’s end time. Inside the function, we’ll declare a clock variable and use it to store a reference to our clock container div. This means we don’t have to keep querying the DOM.
Next, we’ll use setInterval to execute an anonymous function every second. This function will do the following:

Continue reading
Build a Countdown Timer in Just 18 Lines of JavaScript
on SitePoint.

X ITM Cloud News


Leave a Reply

Next Post

SD Times 100 2020: Tear down those walls

Tue Jun 2 , 2020
Spread the love          In today’s rapidly changing software industry, it feels like disruption is happening at a faster pace than at any time in its history. How quickly we’ve gone from SOA to APIs to microservices to containers to serverless! It’s been breathless. This year’s SD Times 100 include many disruptors […]

Cloud Computing – Consultancy – Development – Hosting – APIs – Legacy Systems

X-ITM Technology helps our customers across the entire enterprise technology stack with differentiated industry solutions. We modernize IT, optimize data architectures, and make everything secure, scalable and orchestrated across public, private and hybrid clouds.

This image has an empty alt attribute; its file name is x-itmdc.jpg

The enterprise technology stack includes ITO; Cloud and Security Services; Applications and Industry IP; Data, Analytics and Engineering Services; and Advisory.

Watch an animation of  X-ITM‘s Enterprise Technology Stack

We combine years of experience running mission-critical systems with the latest digital innovations to deliver better business outcomes and new levels of performance, competitiveness and experiences for our customers and their stakeholders.

X-ITM invests in three key drivers of growth: People, Customers and Operational Execution.

The company’s global scale, talent and innovation platforms serve 6,000 private and public-sector clients in 70 countries.

X-ITM’s extensive partner network helps drive collaboration and leverage technology independence. The company has established more than 200 industry-leading global Partner Network relationships, including 15 strategic partners: Amazon Web Services, AT&T, Dell Technologies, Google Cloud, HCL, HP, HPE, IBM, Micro Focus, Microsoft, Oracle, PwC, SAP, ServiceNow and VMware