JavaScript
Article

Build a Countdown Timer in Just 18 Lines of JavaScript

By Yaphi Berhanu

Sometimes in life, you’re going to need a JavaScript countdown clock for something other than a doomsday device. Whether you have an event, a sale, a promotion, or a game, you can benefit from building 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 because you won’t need to load external scripts and style sheets.
  • You’ll have more control because 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.

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:

var deadline = '2015-12-31';

The short format:

var deadline = '31/12/2015';

Or, the long format:

var deadline = 'December 31 2015';

Each of these formats allows you to specify an exact time (in hours minutes and seconds), as well as a time zone (or an offset from UTC in the case of ISO dates). For example:

var 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. To make that happen, we need to write a function that takes a string representing a given end time (as outlined above), and calculate the difference between that time and the current time. Here’s what that looks like:

function getTimeRemaining(endtime){
  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor( (t/1000) % 60 );
  var minutes = Math.floor( (t/1000/60) % 60 );
  var hours = Math.floor( (t/(1000*60*60)) % 24 );
  var days = Math.floor( t/(1000*60*60*24) );
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

First, we’re creating a variable t, to hold the remaining time until the deadline. The Date.parse() function is native JavaScript that 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.

var t = 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:

var seconds = Math.floor( (t/1000) % 60 );

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

  1. Divide milliseconds by 1000 to convert to seconds: (t/1000)
  2. Divide the total seconds by 60 and grab the remainder—you don’t want all of the seconds, just the ones remaining after the minutes have been counted: (t/1000) % 60
  3. Round this down to nearest whole number—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 {
  'total': t,
  'days': days,
  'hours': hours,
  'minutes': minutes,
  'seconds': seconds
};

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:

getTimeRemaining(deadline).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){
  var clock = document.getElementById(id);
  var timeinterval = setInterval(function(){
    var t = getTimeRemaining(endtime);
    clock.innerHTML = 'days: ' + t.days + '<br>' +
                      'hours: '+ t.hours + '<br>' +
                      'minutes: ' + t.minutes + '<br>' +
                      'seconds: ' + t.seconds;
    if(t.total<=0){
      clearInterval(timeinterval);
    }
  },1000);
}

This function takes two parameters: the id of the element that will contain our clock and the end time of the countdown. Inside the function, we’ll declare a variable called clock and use it to store a reference to our clock container div so that we don’t have to keep querying the DOM.

Next, we’ll use setInterval to execute an anonymous function every second, which will do the following:

  • Calculate the remaining time.
  • Output the remaining time to our div.
  • If the remaining time gets to zero, stop the clock.

At this point, the only remaining step is to run the clock like so:

initializeClock('clockdiv', deadline);

Congratulations! You now have a basic clock in just 18 lines of JavaScript.

Prepare Your Clock for Display

Before styling the clock, we’ll need to refine things a little.

  • Remove the initial delay so your clock shows up immediately.
  • Make the clock script more efficient so it doesn’t continuously rebuild the whole clock.
  • Add leading zeros as desired.

Remove the Initial Delay

In the clock, we’ve used setInterval to update the display every second. This is fine most of the time, except in the beginning when there will be a one-second delay. In order to remove this delay, we’ll have to update the clock once before the interval starts.

To do this, let’s move the anonymous function that we are passing to setInterval (the one that updates the clock every second) into its own separate function, which we can name updateClock. Call the updateClock function once outside of setInterval, and then call it again inside setInterval. This way, the clock shows up without the delay.

In your JavaScript, replace this:

var timeinterval = setInterval(function(){ ... },1000);

With this:

function updateClock(){
  var t = getTimeRemaining(endtime);
  clock.innerHTML = 'days: ' + t.days + '<br>' +
                    'hours: '+ t.hours + '<br>' +
                    'minutes: ' + t.minutes + '<br>' +
                    'seconds: ' + t.seconds;
  if(t.total<=0){
    clearInterval(timeinterval);
  }
}

updateClock(); // run function once at first to avoid delay
var timeinterval = setInterval(updateClock,1000);

Avoid Continuously Rebuilding the Clock

To make the clock script more efficient, we’ll want to update only the numbers in the clock instead of rebuilding the entire clock every second. One way to accomplish this is to put each number inside a span tag and only update the content of those spans.

Here’s the HTML:

<div id="clockdiv">
    Days: <span class="days"></span><br>
    Hours: <span class="hours"></span><br>
    Minutes: <span class="minutes"></span><br>
    Seconds: <span class="seconds"></span>
</div>

Now let’s get a reference to those elements. Add the following code right after where the clock variable is defined

var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');

Next, we need to alter the updateClock function to update only the numbers instead of rebuilding the whole clock. The new code will look like this:

function updateClock(){
    var t = getTimeRemaining(endtime);

    daysSpan.innerHTML = t.days;
    hoursSpan.innerHTML = t.hours;
    minutesSpan.innerHTML = t.minutes;
    secondsSpan.innerHTML = t.seconds;

    ...
}

Add Leading Zeros

Now that the clock is updating the numbers instead of rebuilding every second, we have one more thing to do: add leading zeros. For example, instead of having the clock show 7 seconds, it would show 07 seconds. One simple way to do this is to add a string of ‘0′ to the beginning of a number and then slice off the last two digits.

For example, to add a leading zero to the “seconds” value, you’d change this:

secondsSpan.innerHTML = t.seconds;

to this:

secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

If you’d like, you can add leading zeros to the minutes and hours as well. If you’ve come this far, congratulations! Your clock is now ready for display.

Note: You may have to click “Rerun” in the CodePen for the countdown to start.

See the Pen Styled JavaScript Countdown Clock by SitePoint (@SitePoint) on CodePen.

Taking it Further

The following examples demonstrate how to expand the clock for certain use cases. They are all based on the basic example seen above.

Schedule the Clock Automatically

Let’s say we want the clock to show up on certain days but not others. For example, we might have a series of events coming up and don’t want to manually update the clock each time. Here’s how to schedule things in advance.

Hide the clock by setting its display property to none in the CSS. Then add the following to the initializeClock function (after the line that begins with var clock). This will cause the clock to only display once the initializeClock function is called:

clock.style.display = 'block';

Next we can specify the dates between which the clock should show up. This will replace the deadline variable:

var schedule = [
    ['Jul 25 2015', 'Sept 20 2015'],
    ['Sept 21 2015', 'Jul 25 2016'],
    ['Jul 25 2016', 'Jul 25 2030']
];

Each element in the schedule array represents a start date and an end date. As noted above, it is possible to include times and time zones, but I used plain dates here to keep the code readable.

Finally, when a user loads the page, we need to check if we are within any of the specified time frames. This code should replace the previous call to the initializeClock function.

// iterate over each element in the schedule
for(var i=0; i<schedule.length; i++){
  var startDate = schedule[i][0];
  var endDate = schedule[i][1];

  // put dates in milliseconds for easy comparisons
  var startMs = Date.parse(startDate);
  var endMs = Date.parse(endDate);
  var currentMs = Date.parse(new Date());

  // if current date is between start and end dates, display clock
  if(endMs > currentMs && currentMs >= startMs ){
      initializeClock('clockdiv', endDate);
  }
}

Now you can schedule your clock in advance without having to update it by hand. You may shorten the code if you wish. I made mine verbose for the sake of readability.

Count down from When the User Arrives

Sometimes it’s necessary to set a countdown for a given amount of time from when the user arrives or starts a specific task. We’ll use ten minutes here, but you can use any amount of time you want.

All we need to do here is replace the deadline variable with this:

var timeInMinutes = 10;
var currentTime = Date.parse(new Date());
var deadline = new Date(currentTime + timeInMinutes*60*1000);

This code takes the current time and adds ten minutes. The values are converted into milliseconds, so they can be added together and turned into a new deadline.

Now we have a clock that counts down ten minutes from when the user arrives. Feel free to play around and try different lengths of time.

Maintain Clock Progress across Pages

Sometimes it’s necessary to preserve the state of the clock for more than just the current page. For example, if we wanted a ten minute countdown across the site, we wouldn’t want the clock to reset every time the user goes to a different page or every time the user refreshes the page they are on.

One solution is to save the clock’s end time in a cookie. That way, navigating to a new page won’t reset the end time to ten minutes from now.

Here’s the logic:

  1. If a deadline was recorded in a cookie, use that deadline.
  2. If the cookie isn’t present, set a new deadline and store it in a cookie.

To implement this, replace the deadline variable with the following:

// if there's a cookie with the name myClock, use that value as the deadline
if(document.cookie && document.cookie.match('myClock')){
  // get deadline value from cookie
  var deadline = document.cookie.match(/(^|;)myClock=([^;]+)/)[2];
}

// otherwise, set a deadline 10 minutes from now and 
// save it in a cookie with that name
else{
  // create deadline 10 minutes from now
  var timeInMinutes = 10;
  var currentTime = Date.parse(new Date());
  var deadline = new Date(currentTime + timeInMinutes*60*1000);

  // store deadline in cookie for future reference
  document.cookie = 'myClock=' + deadline + '; path=/; domain=.yourdomain.com';
}

This code makes use of cookies and regular expressions, both of which are separate topics in their own right. For that reason, I won’t go into too much detail here. The one important thing to note is that you’ll need to change .yourdomain.com to your actual domain. If you have any questions concerning this, let me know in the comments.

An Important Caveat about Client-Side Time

JavaScript dates and times are taken from the user’s computer. That means the user can affect a JavaScript clock by changing the time on their machine. In most cases, this won’t matter, but in the case of something super sensitive, it will be necessary to get the time from the server. That can be done with a bit of PHP or Ajax, both of which are beyond the scope of this tutorial.

In any case, after getting the time from the server, we can work with it using the same client-side techniques from this tutorial.

Conclusion

We’ve covered how to make a basic countdown clock and prepare it for efficient display. We’ve also gone over scheduling, absolute versus relative times and preserving the clock’s state across page views.

What’s Next?

Play around with your clock code. Try adding some creative styles, or new features (such as pause and resume buttons). If you come up with any cool clock examples you’d like to share, or have any questions about what we’ve covered here, please let me know in the comments.

Yaphi Berhanu
Meet the author
Yaphi Berhanu is a web developer who loves helping people boost their coding skills. He writes tips and tricks at http://simplestepscode.com. In his completely unbiased opinion, he suggests checking it out.
  • Steve Rogers

    This is a very good article. From a programmers’ perspective did you do research such as calculating time and other logic to program with this beautiful code of yours? Sometimes I feel discouraged when I try to program in raw JavaScript without relying on other source material and I can never come up with code like this :(

    • http://simplestepscode.com/ Yaphi Berhanu

      I’m glad you liked the article. JavaScript time is tricky even having worked with it for a while. I did plenty of research for this article to make sure everything was as accurate and thoroughly explained as possible. Definitely don’t feel discouraged if your code doesn’t come out exactly the way you want it the first time. That happens to everyone. One of my favorite ways to get better at JavaScript quickly is to go on Codewars. It’s a really fun set of code challenges at whatever level you want, and you get to see how other people solved the same problems in clever ways. That site is responsible for getting me to a point where a task that used to take 10 lines of code now takes 1.

      • Steve Rogers

        Thank you so much for the tips. And I’ll look into Codewars. Your awesome response really made my day. Thanks!

        • http://careersreport.com Clarisa Turner

          ì want to guíde you to amazíng online work opportunity.. 3-5 h of work a day.. payment at the end of each week.. performance dependíng bonuses…earnings of six to nine thousand dollars /month – merely few hours of your free time, a computer, most elementary familiarìty wìth www and trusted web-connection is what is% needed…learn more by headìng to my page

      • http://adam-recvlohe.squarespace.com/ Adam Recvlohe

        I agree, codewars is very helpful!

  • http://careersreport.com Ida Nichols2

    ì want to guíde you to amazíng online work~ opportunity.. 3-5 h of work a day.. payment at the end of each week.. performance dependíng bonuses…earnings of six to nine thousand dollars /month – merely few hours of your free time, a computer, most elementary familiarìty wìth www and trusted web-connection is what is needed…learn more by headìng to my page

  • http://simplestepscode.com/ Yaphi Berhanu

    That’s a very good point. It’s true that JavaScript intervals do lose accuracy at the rate of a tiny fraction of a second per step. The reasons I chose setInterval for this article:
    a) Browser compatibility
    b) Code simplicity
    c) Unless the countdown needs to be accurate to a fraction of a second, it won’t cause problems

    However, if the countdown needs to have super high precision, I agree that setInterval is not the best method. Thanks for the comment. It’s an important point that people need to be aware of when working with JavaScript time in general.

  • http://jaywilsonjr.com Jay Wilson Jr.

    Great tutorial! I am so glad that you took the time to explain everything in depth. Thank you much! Again, great job, it’s well written and I found it to be quite helpful.

    • http://simplestepscode.com/ Yaphi Berhanu

      Thanks so much. I’m glad you liked it!

  • Jonel

    the best , it helps me alot thanks

    • http://simplestepscode.com/ Yaphi Berhanu

      Glad I could help!

  • http://simplestepscode.com/ Yaphi Berhanu

    I love it! Meteor is an awesome framework, and I like how you’ve used it to get the server time.

    • Gilbert Mizrahi

      Thanks. I am glad you liked it:)

  • Charlie Johnson

    Can this only just be used for one countdown? or can it be used many different times?

    • http://simplestepscode.com/ Yaphi Berhanu

      You can use this on a page as many times as you like.

      The initializeClock function built in this tutorial lets you plug in the id of the div where you want your clock and the desired end time.

      initializeClock(id, endtime)

      Just make sure your div has containers for the numbers. (The CodePen example probably shows the concept better than my comment here.)

  • Kenneth Davila

    That’s cool but why pass e as your jQuery parameter for the plugin, you should just pass $ and follow the pattern recommended by jQuery for plugin authoring, I just found that odd from a readability stand point, as a plugin author myself I have to remember e = jQuery, when majority of plugin authors use $ as recommended.

  • Ilene Skeen

    This is a very helpful tutorial. I actually copied the elements to my development site and made the clock work! Thanks.

    • http://simplestepscode.com/ Yaphi Berhanu

      That’s good to hear!

  • Hassan Hash

    i need your help. i am making a quiz app as my term project using (php and mysql) i have almost completed my project . the only things that is left is countdown timer. Admin should upload the start and the end time of quiz i.e start (2015/09/30 16:00:00) end (2015/09/30 16:30:00) and after time expire quiz should be submitted automatically. i have checked this cannot be implement in php and i dont know javascript on advance level please help me
    thanks

    • http://simplestepscode.com/ Yaphi Berhanu

      If you can access the end time of the quiz through php, then put it in this JavaScript variable:

      var deadline = ‘December 31 2015 00:00:50 UTC+0200’;

      Other than that, copy and paste the example from this tutorial.

  • http://transatlanticwanker.tumblr.com/ James

    Does anyone have any ideas as to why this wouldn’t work on a Tumblr page with a personalised layout? I have the JS and CSS in and tags in the head, and the HTML in the body, and everything works fine except the actual numbers don’t show up. Works fine in codepen, but when I put it together in the “customise” page on Tumblr, it fails to show.

    • http://simplestepscode.com/ Yaphi Berhanu

      Two possibilities:

      1. First make sure Tumblr allows scripts. Put a basic alert in to test this.
      alert(‘hi’);
      If that works, then Tumblr allows scripts.

      2. The document might need to be ready for the script to run properly. (Otherwise, the script would be referring to html elements that don’t exist yet.) Try putting the script as close as possible to the end of the body and see if that makes a difference.

      • http://transatlanticwanker.tumblr.com/ James

        The second one fixed it. Thanks so much.

  • jojot

    what a nice article….. thanks its helping me a lot…

    • http://simplestepscode.com/ Yaphi Berhanu

      Thanks!

  • Rodrigo Pélissier

    Why do you get the 3rd element when looking for a match as yu retrieve the cookie?

    • http://simplestepscode.com/ Yaphi Berhanu

      Normally, if you match a regular expression like this /hello there/g, then it will look for all instances of “hello there” and it will give you something like [‘hello there’,’hello there’,’hello there’].

      However, if you take away the g from the match (to make it not global), then match will give you the phrase, and any capturing groups. A capturing group is anything in parentheses. For example, a match with /(hello) (there)/ would return [‘hello there’,’hello’,’there’].

      That’s why we’re looking for the the third thing. It just happened to be the piece of the expression we were looking for.

  • disqus_8g6crS5sKs

    I just can’t seem to get this to work. I added style info into the head tag, the html into the body followed by the js info in tags. When I add my due date the timer returns “NaN” for days, “aN” for hours, minutes and seconds. If I put the js in the head tag or put it above the html, it doesn’t work at all. Not sure if this is important, but I’m trying to add the timer to a page developed with bootstrap–so it’s referencing external js in the head tag. Does anyone have any suggestions? Thanks.

    • Zichao Lin

      I have had the same problem. I suggest you adhere to the Date format shown in the article, especially when you want to include the GST.

    • http://simplestepscode.com/ Yaphi Berhanu

      1. NaN means “not a number” which means some of the Date inputs aren’t in the correct format (like Zichao Lin said).

      2. If your script comes before your HTML, you’ll need to have some extra code to make sure the document is ready. Otherwise, your script won’t have access to the desired HTML elements because those elements aren’t there yet when the script runs.

      The easier way to fix this is to keep your scripts as close as possible to the tag. That way, you don’t need any extra code, and you’ll get performance improvements too.

      • disqus_8g6crS5sKs

        Thank you! It seems that I somehow made a mistake copying and pasting the javascript. I started over and now it works perfectly. Thanks again!

    • http://mindthegip.com Gip

      In my case the error was in the GMT part.
      In this page is suggested to use this line:
      var deadline = 'December 31 2015 23:59:59 GMT+02:00';
      While the correct way to use the GMT is:
      var deadline = 'December 31 2015 23:59:59 GMT+0200';
      (Without “:”)

      • James Hibbard

        Fixed. Thanks.

  • Zichao Lin

    Fantastic! I just implemented my countdown following this guide.

    However, I encountered some difficulties trying to display the hundredth seconds countdown.

    The displayed hundredth seconds will always be zero, i.e. ..Days, ..(hours) : ..(minutes) : ..(seconds) : 00. (This is how I formatted my countdown).

    It turns out that the last three digits of the milliseconds we obtained from Date.parse() and new Date() are always zeros.

    The solution is simple: use Date.now() instead of new Date().

    I have tried in my console, Date.now() is accurate till the last digit.

    This is how I implemented it:

    function getTimeRemaining(endtime) {
    var t = Date.parse(endtime) – Date.now();
    var hundredth = Math.floor((t % 1000 / 10));

    }

    • http://simplestepscode.com/ Yaphi Berhanu

      Great point! Date.now() is a much better option, and I wish there was a way to highlight your comment.

    • http://simplestepscode.com/ Yaphi Berhanu

      Great point! Date.now() is a much better option, and I wish there was a way to highlight your comment.

    • James Hibbard

      I updated the article to reflect this. Thanks, Zichao.

      • Zichao Lin

        You are welcome.

  • Dan

    Very helpful tutorial! Thanks for the great article.

    • http://simplestepscode.com/ Yaphi Berhanu

      Glad I could help!

  • http://simplestepscode.com/ Yaphi Berhanu

    Try putting a console log right before and after this line:
    initializeClock(‘clockdiv’, deadline);

    That way, you’ll see if the initializeClock function is even getting to run after the first time.

  • http://simplestepscode.com/ Yaphi Berhanu

    Try putting a console log right before and after this line:
    initializeClock(‘clockdiv’, deadline);

    That way, you’ll see if the initializeClock function is even getting to run after the first time.

  • http://www.epubor.com/ Jonny Greenwood

    Hi I have a question, I want to hide the countdown div after the remaining time equals 0, how can I do this? I tried some if statement but doesn’t work.

    • http://simplestepscode.com/ Yaphi Berhanu

      Change this:

      if(t.total<=0){
      clearInterval(timeinterval);
      }

      To this:

      if(t.total<=0){
      clearInterval(timeinterval);
      document.getElementById('clockdiv').style.display = 'none'; // hide the div
      }

  • Toni Bernard Defrees

    This post is great! …and I’m excited to get this working. I have encountered an error “Uncaught TypeError: Cannot read property ‘querySelector’ of null”. I’ve gone as far as copying/pasting your code from Codepen without any success. I had the script in separate file, but have also tried moving it into the file without any luck either. Do you have any suggestions?

    • http://simplestepscode.com/ Yaphi Berhanu

      If querySelector is causing an error, that means the script is not finding the HTML elements it needs to find.

      One of two things could be causing this:

      1. Maybe the script is being loaded before the HTML is loaded. To fix this, put the script as close as possible to the end of the body (doesn’t matter whether it’s in an external file or not). That way, the page elements will have time to load before the script tries to do anything.

      2. Maybe the class names of the elements have been changed (so when it looks for .minutes for example, it won’t find anything).

      • Toni Bernard Defrees

        Thank you! Yes, the script was loading before the HTML. I moved it tot he bottom of the file. Thanks again!

  • Toni Bernard Defrees

    This post is great! …and I’m excited to get this working. I have encountered an error “Uncaught TypeError: Cannot read property ‘querySelector’ of null”. I’ve gone as far as copying/pasting your code from Codepen without any success. I had the script in separate file, but have also tried moving it into my html file without any luck either. Do you have any suggestions?

  • http://appletite.tumblr.com/ Alex

    Since there are 1000 ms in one second….total will never equal 0…so the following statement will never evaluate to be true and the clear interval timer won’t fire and the countdown will continue into negative numbers.

    Change this line of code:

    if (t.total <= 0) {
    clearInterval(timeinterval);

    }

    to be this instead

    if (t.total <= 1000) {
    clearInterval(timeinterval);

    }

    When seconds hits "00"….t.total still has a value of 994. And 1000 (the setInterval timer) – 994 does not equal 0.

    • http://simplestepscode.com/ Yaphi Berhanu

      Good catch about the 994. It actually came from a recent change with some unexpected side effects (my fault for not realizing this would be an issue).

      It turns out that using Date.now() instead of Date.parse(new Date()) takes away the millisecond rounding that used to make this clock stop at zero.

      Originally, the clock would go down to 0, and then the (t.total <= 0) would check that it equaled zero (or less in case of imprecision). That worked perfectly until the switch from Date.parse(new Date()) to Date.now().

      Two fixes that will both work:

      1. Replace Date.now() with Date.parse(new Date()) to remove the 994ms issue.

      2. Using (t.total < 1000) would fix the issue while removing the equals sign would prevent the clock from stopping 1 second too early.

  • Craig Morrison

    Question: you began the article with the var deadline and after that, referred to endtime. Is that a mistake or did I miss where endtime was declared and what it was meant to hold? Sorry if this is a bothersome question… By the way, I thought it was a fantastic article with very elegant JS code. ;)

    • Craig Morrison

      I think I figured it out… Correct me if I’m wrong, but I think endtime is just an argument name when defining functions here, which eventually get actual values passed into them, for example, when deadline is passed into the function.

      • http://simplestepscode.com/ Yaphi Berhanu

        You’re exactly right! It is an argument name, and the actual value gets passed in later. Glad you enjoyed the article.

  • Matt Breckenridge

    This definitely a factor of my inexperience, but I’m completely confused by setting the deadline. I’m not clear on how the var deadline = … relates to the countdown clock, because the clock in the CodePen doesn’t seem to include that line of code anywhere. Can you clarify how the deadline variable factors into and is implemented by the rest of the script?

    • http://simplestepscode.com/ Yaphi Berhanu

      This line at the very end is the key:

      initializeClock(‘clockdiv’, deadline);

      Basically the initializeClock function takes two parameters:
      1) The id of the html element where you want the clock to show up
      2) The time when the clock should end

      When we run the clock, we’re specifying that we want it to appear in the element with the id of “clockdiv”, and we want it to expire at the deadline we set.

      Hopefully this helps!

      • Matt Breckenridge

        Thanks very much for the reply. It got me on the right track to bumble my way through and learn something.

      • Matt Breckenridge

        Thanks very much for the reply. It got me on the right track to bumble my way through and learn something.

  • Vince Anderson

    I’m new to javascript and I’m pretty sure that I’m missing something fundamental.

    I’ve gone through the entire tutorial, and I’ve even gone as far as to created a blank html file and copy and paste the exact code from http://codepen.io/yaphi1/pen/bdOMej?editors=101, I’ve included everything in the html inside of tags, and referenced it in an external .js file. I’ve tried it in several different locations with no luck.

    Am I missing something? Could it be some type of server configuration thing that I’m missing?

    Thanks for the help.

    Vince

    • http://simplestepscode.com/ Yaphi Berhanu

      The html shouldn’t be in script tags, but the js should be.

      Also, put the script as close as possible to the end of the body (the script can be external or not depending on your preference). The script needs to run after the html is there; otherwise it won’t have any html elements to put the clock in.

      I hope this helps!

  • http://www.bobborst.com Bob Borst

    I wanted to have a message display once the countdown has completed. To do this I added a third parameter to the function in the HTML. In this case ‘Happy New Year’:

    initializeClock(‘clockdiv’, deadline, ‘Happy New Year’)

    In the JavaScript I added the new parameter to the function:

    function initializeClock(id, endtime, message)

    And once the countdown has completed I display the message:

    if (t.total <= 0) {
    clearInterval(timeinterval);
    document.getElementById(id).innerHTML = message;
    }

  • http://simplestepscode.com/ Yaphi Berhanu

    The script needs to come after the clock div. Otherwise, when the script looks for the clock div and tries to update the numbers, it won’t find anything because the clock div doesn’t exist yet. I hope this helps!

  • अर्जुन के.आर.

    Thank you very much for sharing a very nice, quite easy timer!!

    • http://simplestepscode.com/ Yaphi Berhanu

      Glad you liked it!

  • Nick F.

    Out of curiosity, if I was to use something like this, would there be a way to replace the text or the counter or even load something new when the counter gets down to zero?

    I’m guessing it would be adding some sort of function into the if statement that checks for a 0 state in the counter to do that work, but it’s been YEARS since I’ve worked in JS, so I just don’t want to overthink the problem too much.

    • http://simplestepscode.com/ Yaphi Berhanu

      Yup you can do that.

      Replace this:
      if(t.total<=0){
      clearInterval(timeinterval);
      }

      …with this:
      if(t.total<=0){
      clearInterval(timeinterval);

      // do whatever you want here

      clock.innerHTML = "Here's an example message.";

      }

      • Ramya

        Hi Yaphi, Thank you very much for this code, I would really appreciate if you could help with the stopping of the clock moment it reached the specified time which is mentioned in the argument when we call the ‘initializeClock’ function

        Please advise me, also I need a pop up message to say the User: ‘Time out, Please try again!’ after this popup timer has to reset till start button activated;

  • http://simplestepscode.com/ Yaphi Berhanu

    It’s probably just getting interference from other cookies on the page. Try this instead:

    var deadline = document.cookie.match(/(^|;|s)myClock=([^;]+)/)[2];

  • http://simplestepscode.com/ Yaphi Berhanu

    Here’s one way to make a reset button.

    First, change this line:

    var timeinterval = setInterval(updateClock, 1000);

    …to this:
    window.timeinterval = setInterval(updateClock, 1000);

    Then add this to your HTML:
    Stop the clock

    Finally, add this at the very end of your script:
    function stopClock(){ clearInterval(timeinterval}; }
    document.getElementById(‘stopbutton’).onclick = stopClock;

    • Aaron Noah Horvitz

      For some reason it makes the clock go blank.

  • http://simplestepscode.com/ Yaphi Berhanu

    If you see “NaN” or something like that, it means “Not a Number”. That means the format of the number got messed up somehow. The fix is to copy the code from this tutorial and make sure the numbers are formatted correctly.

    • http://azurelunatic.livejournal.com AzureLunatic

      I found that the deadline in the format
      var deadline = ‘December 31 2015 23:59:59 GMT+02:00’;
      as seen in this tutorial worked for Chrome and Firefox, but not IE (bless its heart).
      The format yyyy-mm-ddTxx.xx worked for all three, at the expense of apparently not being able to specify a time zone.

  • JCC

    I am a JS amateur but eventually figured out how to get this going, and it is perfect! One small suggestion–I used the “Get on a page and count down” function–it would be nice if the seconds displayed a leading zero when they were single digits, rather than just one character. I have it at 2 minutes and I’d like it to say 1:01 rather than 1:1 which it does (I took out the minutes and seconds labels.) I do not know how to do that. But otherwise, perfect!

  • JCC

    Let me ask another question–I would like to format the output and CSS does not seem to affect the text. When I tried to format it in the JS itself, it broke. I’m sure I’m overlooking something, but this has not worked either way.

    • JCC

      Inline formatting on the clockdiv div worked. Shoulda thought of that yesterday, but I was so happy with this!

  • http://skilledacademy.com Alvaro

    Hi! thanks for the great article. I created the countdown timer with the cookie so that when the countdown hits 0 a message shows up “offer has expired”.
    It works great! :-)
    If I want the code to act like this:
    if countdown hit 0 then wait 5 sec, display “offer has expired.” then load another page…
    how could I code it?

    • Jared

      You could use a conditional (an if statement) to check if the current time is greater than or equal to the deadline time.

      You would stick something like this into the updateClock function:

      if (currentTime >= deadline) {

      clearInterval(timeInterval);

      countdownEnded();
      }

  • Becky

    Someone help pls…. I copy pasted all codes to the index.html file and put css and js codes internally as well. Everything is cool but there is only a problem that timer doesn’t work. Design is in super shape but there is no any timer running ( I attempted to move js codes botttom to the closing body tag and to top. but no result. pls help

  • http://shoppe.ca Stephan Hoppe

    Wow, that was nasty, unnecessary, and poorly written in that you kind of make the same two complaints four times. Sometimes I actually appreciate possibly inefficient code that I can understand as I am learning rather than super-streamlined OOP that’s indecipherable.

  • oliver

    Great plugin but I was wondering if it is possible to add it to a lightbox with the seconds and minutes counting down?

    Thanks

  • https://www.aamediaprojects.com Arno Agten

    Everyt ime I reload the page it restarts the countdown, i want to countdown to a specific date, could you help me modifying the code so I could get that to work?

  • Jay Gibble

    Great stuff – I’m trying to figure out how to get the value of the current time when pausing the counter. Any insite? Thanks

  • Muditt Chauhan

    Please tell me how to create cookie myClock. I am beginner and I really want this cookie code for my project. Any help is appreciated.

  • Stephanie Socias

    This is great- thank you so much! One question, though, should it work on mobile devices? It works great on my laptop but when I try on my phone, the numbers are replaced with “NaN” and “aN”…?

  • Michael Kristiansen

    Thank you for a very informative and educational article. I really like they way you explain every part of the script.

  • Ghassan Safadi

    Great and very useful code…Thank you…I was not sure if can be used for Time to open and time to close based on json source that has the start and end date and time that repeats every week..

  • Alexander

    How do I link the javascript file , and what should I name it?
    Thanks

  • HarrisG

    The best. Your commitment to knowledge sharing is a blessing. Many thanks.

  • Josh Brown

    I would like to have 2 different countdowns running at the same time. How would I do this? without having them interfere with each other. The two countdowns have 2 different deadlines.

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.