By Yaphi Berhanu

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:


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;

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;

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>

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: = '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
  // 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=/;';

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 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.


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.

  • 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 :(

    • 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!

        • ì 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

      • I agree, codewars is very helpful!

  • ì 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

  • 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.

  • 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.

  • Jonel

    the best , it helps me alot thanks

  • 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?

    • 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.

  • 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

    • 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.

  • 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.

    • Two possibilities:

      1. First make sure Tumblr allows scripts. Put a basic alert in to test this.
      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.

      • The second one fixed it. Thanks so much.

  • jojot

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

  • Rodrigo Pélissier

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

    • 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.

    • 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!

    • 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 instead of new Date().

    I have tried in my console, is accurate till the last digit.

    This is how I implemented it:

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


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

    • Great point! 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.

      • loger

        Can you help me please with something from this article?

        • James Hibbard

          I can try. What do you need?

        • James Hibbard

          Sure. What exactly?

  • Dan

    Very helpful tutorial! Thanks for the great article.

  • 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.

  • 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.

  • 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.

    • Change this:


      To this:

      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?

    • 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?

  • 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 ( <= 0) {


    to be this instead

    if ( <= 1000) {


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

    • 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 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 ( <= 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

      Two fixes that will both work:

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

      2. Using ( < 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.

      • 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?

    • 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.

      • Yamado

        Still confused here. Tell a layman :). Where exactly do we plug in the var deadline = ‘December ## #### 23:59:59 GMT+0200’;

        In the js, it reads: var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
        initializeClock(‘clockdiv’, deadline);

        I don’t see any instruction exactly where to place our deadline

        • Sebastian Cruz

          This is how you want to set the deadline variable:

          // Christmas is coming!
          var deadline = new Date(Date.parse(‘December 25 2016 00:00:00 GMT+0000’));

          Hope this helps!

          • David Dumonde

            This totally solved it for me. Thanks!

      • Yamado

        The most important part for laymen, which isn’t properly explained.

        In short, where we see in the codepen example: “var deadline = new Date”, replace “new Date” with the deadline… eg: “var deadline = ‘December 31 2015 23:59:59 GMT+0200’;(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);”

        The problem with the guide is the example at the top doesn’t show the line completed. Which is misleading for a newbie. The guide shows only “var deadline = ‘December 31 2015 23:59:59 GMT+0200’;” (without the (Date.parse(……….. portion of the line, which needs to be there for the code to work).

  • 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, 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.


    • 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!

  • 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 ( <= 0) {
    document.getElementById(id).innerHTML = message;

  • 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!!

  • 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.

    • Yup you can do that.

      Replace this:

      …with this:

      // 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;

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

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

  • 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.

  • 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.

    • 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!

  • 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) {



  • 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

  • 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?


  • 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?

  • 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.

  • Tamara

    Hi! I am trying to have the counter restart every 7 days for a raffle. The raffle would end every sunday night at 8pm ct. How can I do that?

    Thank you!!

  • Patty Bradley

    Thank you so much Yaphi! Your code works great and all the explanations really help. Keep up the good work!

  • Oriana Marquina

    It work excellent for me :) thanks

  • ssk


    where to right this function and var deadline var

  • ssk

    where to wright this function getTimeRemaining(deadline).minutes
    and var deadline?

  • kb

    Hi, is it possible to loop indefinitely? We have an FTP server that updates every 30 minutes and this would help by tell me how much more time is left. I will eventually tie in via ajax but need to learn that.

  • kb

    is it possible to loop forever? Got it to a 30 min countdown, looking to sync the clock based on an ftp refresh cycle that we don’t have access to. a stretch but I never know where in the 30 minutes I am at any given time. Plan to keep refreshing until I see an update and start the clock at that time.

  • Aku

    this is a great article very insightful thank you

  • Hastings

    This is cool, Yaphi, thanks a lot.

    Thought one question:
    The starting point is mostly the current (computer time).

    Can I not create a dropdown, where I can simply choose then some endpoints (deadline) like:

    – at 8 pm on the same day
    – at 10 am in the following day
    – in 10 days

    This would be very convenient, instead always had to change the code.
    But to be honest, I tried, but withouth any success.

    Do you or another “javascipt-crack” has some hints or a solution.
    Would be really great, thanks in advance.

    Best wishes from Switzerland.

  • Juan Carlos Guerrero Fernandez

    Good morning I have a question, I want to use it, but I see the same time in all browsers.
    I want to say that if I open the browser now and spend 10 minutes, I open the other browser and that ten minutes I happened to tell them not to restart the browser
    What could I do?
    I hope they help me

  • Sara Terry

    I noticed in your final code snippet the clock always counts down from 15 days and this resets when the browser is refreshed. How do you do it so it’s always counting down to a certain date? I tried using that code and changing ‘var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);’ to ‘var deadline = new Date(Date.parse(new Date()) + ’12/01/2017′);’ but I don’t think this is right/it didn’t work.

    • Leif Sture

      read the section about it.
      “Schedule the Clock Automatically”.

      Add a timezone to the schedule to sync it. So there arn’t different countdowns in different timezones. This makes it so you can start the clock, stop it at a certain time and continue when you want. If you want to show a message inbetween the stops then read the first comment by “Bob Borst”. You can use the same method as he describes for doing that.

      A way to change the countdown for the user is to change the timesettings on the computer. I don’t concider that a big problem for my use, but if you want to remove this option for the user then sync the clock to the server. You can do that with ajax or php.

  • Thomas Somme

    Thanks for sharing your code with us. The clock is looking great !
    However I tried to run the code but the console says “null is not an object (evaluating ‘clock.querySelector’)” …
    Everything is displayed excepted the time. Why ? I even tried just to copy/paste the code you made on codepen into my html page … I can’t see the countdown … If you could help me that would be nice :-)
    Thanks anyway !

  • Katie Difford

    Hello there,
    I have a question about this article and wonder if you could help me with it.


  • dmorg

    Fair enough, as far as it goes. But suppose I want to know the time until some event in the future, in a different timezone, and compensating for leap years, daylight saving time, etc.? That’s what has me stumped.

  • James Higgins

    I’m having an issue initializing for then 2 timers on a page, I’m just reinintializing like so on different divs:

    initializeClock(‘clockdiv’, deadline);
    initializeClock(‘clockdiv1’, deadline);
    initializeClock(‘clockdiv2’, deadline);
    initializeClock(‘clockdiv3’, deadline);

    It stops working at number 2 though, any ideas?

    Thanks for the code!

  • Do you have video tutorial of this article ??. If you have please share the link. Thanks

  • Dennis Tabaldo

    Nice one.

  • hallibus

    Hey! Thanks for the Script, but i have one issue: I nested the “clockdiv” in 2 other divs. The remaining time is calculated on first load and applied to the spans, but updating the clock doesn’t work. I see the changes in the console, but the spans aren’t updated. Any ideas? Thanks in advance!

  • Diablo1234

    This clock reset everytime you refresh the page. How do you make it count down to a specific date in the future?

  • Marko Blašković

    Very nice work there. I have one question, since I am not so familiar with js. How can I speed up the clock? So let’s say, 10 seconds passes in 1 second or something similar, but with all the seconds passed shown in the clock (otherwise I know how to do that :) when the clock skips 10 or more seconds ). What do I have to change?

  • Ahmed Kabir Maruf

    Hey Yaphi, this timer restarts if I refresh the page. And the cookie thing is not working. Maybe I didn’t put it properly in my code. Can you please give me the whole #JS code of a timer that doesn’t restart on page refresh? I need it so bad. Please help me. Thanks.

  • ola

    Hi. Please how to i feed a dynamic deadline/endtime to the script(a variable) Thanks for sharing

  • Very Beautiful Clock. Beautiful UI. Beautiful logic.

  • Jeremy Smith

    Awesome tutorial, thanks very much!

  • Axel Precious Blaze

    I have successfully implemented this your code is working perfectly i would like to know how i would

  • Drew

    Great Snippet! I am having one issue though..

    I am trying to keep the timer running via Maintaining Clock Progress but seem to be breaking it.. Your instructions seem simple enough ie: “replace the deadline variable with code you provided” but when I do, it seems to not work at all.

    I replace: var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000); initializeClock(‘clockdiv’, deadline);


    // 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
    // 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=/;’;

    BUT following your instructions to “replace” does not seem to work. I am probably missing something? I just want the timer to keep running until it expires.


  • Sergey Pronin

    Yaphi, thank you bro! I tried several plug-ins, but your lesson is the best and I understood everything though I do not know js

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