October 19, 2015 10:31 pm

Creating a countdown timer with Vanilla JavaScript

Adding a timer with JavaScript to a website can be useful for various purposes. The countdown can be counting the days left to the official launch of your website, product or feature within the website. Relying on third-party libraries can cause extra burden on the bandwidth involve and it can    lose some of your time trying to bend the library to your will. If all you need is a simple countdown timer, the code involved is not that much to need the involvement of third-party scripts.
Creating a countdown timer with Vanilla JavaScript

[wpdm_file id=151]DEMO

To use our countdown timer, all that you are going to need to do is call the addCountdown function, pass it a date string and an element where the countdown will go and you are set. Using it looks something like this:

addCountdown('09/01/2015', "countdown");

You need one line of JavaScript and one line that adds the element where you want it to be in the DOM:

<div id="countdown"></div>

The result is a countdown timer like this one:

Creating a countdown timer

The visuals

We have created a simple dark skin for the countdown timer.

We float each box (there are 4 boxes – with days, hour, minutes and seconds) to the left, give fixed dimensions to the countdown timer and its boxes, make it dark and highlight the boxes with white border. We also use the default cursive font available to the system.

#countdown > div {
  font-family: cursive;
  float: left;
  margin: 1em;
  background-color: #111;
  color: #eee;
  padding: 15px;
  border: 4px solid #eee;
  height: 40px;
  width: 90px;
}
#countdown {
  background-color: #444;
  width: 650px;
  min-height: 120px;
}

The logic

function addCountdown(targetDate, elementId, timeLabelArray) {

We create our function which accepts a date to countdown to, the id of the element which we want to hold the countdown timer and an optional array with labels for the time values. It seeks for 4 elements in the following order – days, hours, minutes, seconds. For example, if we pass it an array like: [“Дни”, “Часа”, “Минути”, “Секунди”] the labels will be in Bulgarian as shown in the picture below:

Creating a countdown timer1

To achieve this, we just called the addCountdown function in the following manner:

addCountdown('09/03/2015', "countdown", ["Дни", "Часa", "Минути", "Секунди"]);

In the body of the addCountdown function we define another function called timeRemaining which will determine how many days, hours, minutes and seconds remain to the target date and return them as a string combined with the appropriate time label.

function timeRemaining() {
timeLabelArray = timeLabelArray || ['Days', "Hours", "Minutes", "Seconds"];
var timeRemaining = new Date(targetDate).getTime() - new Date().getTime();
if (timeRemaining > 0) {

var secondsRemaining = Math.floor(timeRemaining / 1000 % 60),
minutesRemaining = Math.floor(timeRemaining / 1000 / 60 % 60),
hoursRemaining = Math.floor(timeRemaining / 1000 / 60 / 60 % 24),
daysRemaining = Math.floor(timeRemaining / 1000 / 60 / 60 / 24);
return [daysRemaining + ' ' + timeLabelArray[0], hoursRemaining + ' ' + timeLabelArray[1],
minutesRemaining + " " + timeLabelArray[2],
secondsRemaining + " " + timeLabelArray[3]];
}
return null;
}

Afterwards, we define yet another function which takes the return value from the timeRemaining function and if timeRemaining has returned null we stop updating the clock every second and remove the countdown container (it returns null if the UNIX timestamp holds a negative value as checked in  if (timeRemaining > 0) )

function isCountdownEnded(times) {
if (!times) {
clearInterval(moveClock);
document.getElementsByTagName("body")[0].removeChild(
document.getElementById(elementId)
);

return true;
}
return false;

}

Then, we call timeRemaining and save the return value to a variable:

var times = timeRemaining();

Now, in our main addCountdown function we call isCountdownEnded and return from it if the result of the call to isCountdownEnded contains a truthy value:

if (isCountdownEnded(times)) return;

Progressing further, we add all necessary children to the container element for the countdown timer with their appropriate value:

document.getElementById(elementId).innerHTML = "<div id='cdtimer-days'>" + times[0] + "</div>" +
"<div id='cdtimer-hours'>" + times[1] + "</div>" +
"<div id='cdtimer-minutes'>" + times[2] + "</div>" +
"<div id='cdtimer-seconds'>" + times[3] + "</div>";

times is an array that comes as a result of the call to timeRemaining.

Finally, we set an interval that will call timeRemaining, stop further execution if the timer’s time is up and which will update the remaining time each second.

var moveClock = setInterval(function() {

var times = timeRemaining();
if (isCountdownEnded(times)) return;
document.getElementById("cdtimer-days").innerText = times[0];
document.getElementById("cdtimer-hours").innerText = times[1];
document.getElementById("cdtimer-minutes").innerText = times[2];
document.getElementById("cdtimer-seconds").innerText = times[3];

}, 1000)

Author Ivan Dimov

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.biz. facebook, twitter


Tutorial Categories:

4 responses to “Creating a countdown timer with Vanilla JavaScript”

  1. Syed Faizan Ul Haq says:

    Thank you Ivan 🙂

  2. Ivan Yosifov says:

    Why is it not animated?

  3. Green Life IT says:

    this is very cool…..

  4. Green Life IT says:

    this is very cool…..

Leave a Reply

Your email address will not be published. Required fields are marked *