Simple Pure Javascript Countdown Timer (Free Download)

Welcome to a tutorial and example on how to create a simple Javascript Countdown Timer. Need to do a countdown for the launch of an event, store, or product? Or a timer for an offer? Let us walk through one in this guide – Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

TABLE OF CONTENTS

Download & Demo How It Works Useful Bits & Links
The End

 

 

DOWNLOAD & DEMO

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

HOW TO USE & DEMO

SIMPLE COUNTDOWN

1-simple.html
<!-- (A) LOAD LIBRARY & THEME -->
<link href="countdown-dark.css" rel="stylesheet">
<script src="countdown.js"></script>
 
<!-- (B) GENERATE COUNTDOWN TIMER HERE -->
<div id="demoA"></div>
 
<!-- (C) ATTACH COUNTDOWN TIMER -->
<script>
counter.attach({
  target : document.getElementById("demoA"),
  remain : 5400 // 90 mins = 5400 secs
});
</script>

This is as straightforward as can be.

  1. Load the Javascript and CSS. Doh.
  2. Create an empty <div> where you want the countdown timer.
  3. Use counter.attach() to create the countdown timer.
    • target The HTML <div> to generate the timer in.
    • remain Time remaining, in seconds.

 

RUN FUNCTION ON TIME END

2-on-end.html
counter.attach({
  target : document.getElementById("demoB"),
  remain : 65,
  after : () => { console.log("TIMER HAS ENDED!"); }
});

Just provide an additional after : FUNCTION in the options.

 

COUNTDOWN TO GIVEN DATE

3-to-date.html
// FOR THIS EXAMPLE, WE TAKE 2 DAYS FROM NOW
// IN YOUR PROJECT THIS IS NEW DATE("YOUR TARGET DATE/TIME")
var till = new Date(Date.now() + 172800000);
 
// ATTACH COUNTDOWN
counter.attach({
  target : document.getElementById("demoC"),
  remain : counter.toSecs(till)
});

Use counter.toSecs(new Date("TARGET DATE")) to help you.

 

 

COUNTDOWN TIMER – HOW IT WORKS

Now that we are done with the basic usage, here are more details on how the countdown timer works.

 

PART 1) INITIALIZE – ATTACH COUNTDOWN TIMER

countdown.js
// (A) HELPER - CREATE HR/MIN/SEC CELL
// txt : text for the cell (all small letters)
square : (txt) => {
  let cell = document.createElement("div");
  cell.className = `cell ${txt}`;
  cell.innerHTML = `<div class="digits">0</div><div class="text">${txt}</div>`;
  return cell;
},
 
// (B) INITIALIZE COUNTDOWN TIMER
// target : target html container
// remain : seconds to countdown
// after : function, do this when countdown end (optional)
attach : (instance) => {
  // (B1) GENERATE HTML
  instance.target.className = "countdown";
  if (instance.remain >= 86400) {
    instance.target.appendChild(counter.square("days"));
    instance.days = instance.target.querySelector(".days .digits");
  }
  if (instance.remain >= 3600) {
    instance.target.appendChild(counter.square("hours"));
    instance.hours = instance.target.querySelector(".hours .digits");
  }
  if (instance.remain >= 60) {
    instance.target.appendChild(counter.square("mins"));
    instance.mins = instance.target.querySelector(".mins .digits");
  }
  instance.target.appendChild(counter.square("secs"));
  instance.secs = instance.target.querySelector(".secs .digits");
 
  // (B2) TIMER
  instance.timer = setInterval(() => { counter.ticker(instance); }, 1000);
},

Yikes, this looks very complicated, but keep calm and look carefully.

  • counter.attach() is exactly what we called to create the countdown timer. All it does is generate the HTML and do a setInterval() to start the timer.
  • counter.square() is a helper function to create the day/hour/minute/second HTML cell.

That’s all.

 

 

PART 2) COUNTDOWN TICKER

countdown.js
// (C) COUNTDOWN TICKER
ticker : (instance) => {
  // (C1) TIMER STOP
  instance.remain--;
  if (instance.remain<=0) {
    clearInterval(instance.timer);
    instance.remain = 0;
    if (typeof instance.after == "function") { instance.after(); }
  }
 
  // (C2) CALCULATE REMAINING DAYS/HOURS/MINS/SECS
  // 1 day = 60 secs * 60 mins * 24 hrs = 86400 secs
  // 1 hr = 60 secs * 60 mins = 3600 secs
  // 1 min = 60 secs
  let secs = instance.remain;
  let days = Math.floor(secs / 86400);
  secs -= days * 86400;
  let hours = Math.floor(secs / 3600);
  secs -= hours * 3600;
  let mins = Math.floor(secs / 60);
  secs -= mins * 60;
 
  // (C3) UPDATE HTML
  instance.secs.innerHTML = secs;
  if (instance.mins !== undefined) { instance.mins.innerHTML = mins; }
  if (instance.hours !== undefined) { instance.hours.innerHTML = hours; }
  if (instance.days !== undefined) { instance.days.innerHTML = days; }
},

This looks intimidating again, but just take a minute to study the code. All it does is decrement the remaining seconds by 1, then update the HTML.

 

 

PART 3) COUNTDOWN TO GIVEN DATE

countdown.js
// (D) HELPER - CONVERT DATE/TIME TO REMAINING SECONDS
// till : (date object) countdown to this date/time
toSecs : (till) => {
  till = Math.floor(till / 1000);
  let remain = till - Math.floor(Date.now() / 1000);
  return remain<0 ? 0 : remain;
}

counter.attach() only takes in the remaining time in seconds. So this is a small helper function to automatically calculate the remaining seconds till the given date.

 

EXTRA) COUNTDOWN HTML

<div id="ID" class="countdown">
  <div class="cell days">
    <div class="digits">00</div>
    <div class="text">days</div>
  </div>
  <div class="cell hours">
    <div class="digits">00</div>
    <div class="text">hours</div>
  </div>
  <div class="cell mins">
    <div class="digits">00</div>
    <div class="text">mins</div>
  </div>
  <div class="cell secs">
    <div class="digits">00</div>
    <div class="text">secs</div>
  </div>
</div>

For you guys who are curious, here is what the Javascript will generate.

 

 

USEFUL BITS & LINKS

That’s it for all the code and examples, and here are some extras that may be useful to you.

 

PLAY ALARM AFTER TIME ENDS?

<script>
var alarm = new Audio("ALARM.MP3");
counter.attach({
  target : document.getElementById("TARGET"),
  remain : 123,
  after : () => { alarm.play(); }
});
</script>

 

COMPATIBILITY CHECKS

This countdown timer will work on all modern browsers.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end of this short guide. I hope that it has helped you to create a better project, and if you have anything to share with this guide, please feel free to comment below. Good luck and happy coding!

5 thoughts on “Simple Pure Javascript Countdown Timer (Free Download)”

  1. How do you stop the counter from showing negative values once it’s done running ? Is there a function to add that will just show zeros? I’m talking about the 3-countdown that shows hours/minutes/seconds.

      1. That was a tiny but oneumental fix – thanks! FYI your code pasted in with a space between < and = which would cause an error. That may be a bug in the textbox parsing. At any rate – thanks a million!

  2. Good time of day!
    I have a question for you.
    1. As in the countdown timer (year, day, month, hours and seconds), add a gif picture. And below, put your countdown timer?
    2. How to add the input of the reference date via JS?
    3. How to connect melody playback at the end of the countdown?

    1. 1) Just put a <img src="xyz.gif"> image tag below the countdown timer? You might want to go through the basics of HTML and CSS.
      2) As described in section B – Just set counter.end = Date.UTC(2020, 0, 1, 0, 0, 0);
      3) Create an HTML audio tag <audio id="alarm-sound"><source src="sound.ogg"></audio>, play sound when time is 0 or less if (counter.end <= 0) { document.getElementById("alarm-sound").play(); }

      HTML Audio Tag reference - https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio

Leave a Comment

Your email address will not be published.