Industry guru Dave Taylor answers free tech support questions about a wide variety of business and technical topics, including blogging, Google AdSense, MySpace, Sony PSP, Apple iPod, Mp3 players, management, Linux, SEO, Mac OS X, Facebook, Twitter, LinkedIn and Microsoft Windows.

How do I create a JavaScript countdown timer on my Web page?

Dave, being a new web developer I would like to know how I can code for a numeric value to decrease by 1 every 24 hours based on the local time function.

Specifically, we are trying to create a reminder for our employees of an upcoming DoD audit in the facility. The count down will represent the number of days remaining before it's conducted. So what I need to do is begin with a date and start the countdown from there. What is the code that I should use?


Dave's Answer:

This is an obvious situation where JavaScript is going to be your friend, and it turns out that this is a straightforward application of JavaScript so it should be fairly easy.

The key is to realize that JavaScript is a so-called object oriented programming language and that it has a specific date object with "methods" that let you set and extract specific values. But, really, this task is even easier than that, because all we need to do is set a specific target date in the future, get the current date, then calculate the amount of time between them and divide it out so that we end up with days as the value.

You get the current date in JavaScript with new Date(), and it turns out that if you specify a date in the parens, it instantiates (creates) a new object with the specified date, rather than today. Want to have a date object with 28 February, 2005 as the specified date? Use new Date("28 February, 2005") and it'll work just fine.

Then we want to work with what us Unix types call the "epoch time" which is the number of milliseconds since a fixed point in the past. For convenience, it's 1 Jan, 1970 on most systems, but if you think about it you'll realize that it doesn't matter what date the epoch time starts with, as long as it's consistent across both values. Anyway, let's see some code!

<script language="javascript" type="text/javascript">

today  = new Date();
todayEpoch  = today.getTime();

target = new Date("28 February, 2005"); 
targetEpoch = target.getTime();

daysLeft = Math.floor(((targetEpoch - todayEpoch) / (60*60*24)) / 1000);
</script>

This JavaScript code snippet, which I'd put in the HEAD of my document, calculates the number of days left until the target date and saves it in the variable daysLeft. Notice that since we're actually working in milliseconds and we want days, we need to divide by 1000 to get seconds, then divide by 60 (to get minutes), 60 again (to get hours) and then 24 (to get days). Finally, we use the mathematical floor function to make sure we don't get weird values like 23.434233 days or similar, as a convenience.

Whenever you want to actually include that value on the page, simply add a single line of JavaScript within the HTML code:

<script>document.write(daysLeft);</script>

To put it all together, here's a simple little page that has both JavaScript code pieces displayed:

<html>
<head>
<title>JavaScript Countdown timer test</title>

<script language="javascript" type="text/javascript">

today  = new Date();
todayEpoch  = today.getTime();

target = new Date("28 February, 2005"); 
targetEpoch = target.getTime();

daysLeft = Math.floor(((targetEpoch - todayEpoch) / (60*60*24)) / 1000);
</script>

</head>
<body>

<h1>DoD inspection in

<script>document.write(daysLeft);</script>

days. Are you ready?
 </h1>

</body>

I hope that'll help you create what you need on your site, and good luck with your DoD inspection too!



Help others find this article at Del.icio.us, Digg, Netscape, Reddit, and Simpy.

Subscribe!

Never miss another useful Q&A article again! Subscribe to AskDaveTaylor with Google Reader.

Comments

I'd just like to point out, because this is javascript, its client side. So it will use whatever system time the user's computer is set at. Not saying your user's will have their local computer's system dates set so bad it will make a difference, but I just wanted to point out its totally on their side. If you have some sort of server side technology at your disposal, such as ASP, ASP.NET, JSP, etc, then you could better control it. Such as by setting seed value and then letting the client side javascript take the count down from there.

Posted by: David Hergert at February 1, 2005 3:01 AM

Absolutely right, David. Since the person submitting the question was talking about a controlled work environment, I made the leap that they'd have standardized on a network time synchronization protocol and everyone would have the correct time on their computers, plus or minus a few seconds. If that's not true, then some people are definitely going to see odd results, but perhaps we can conclude that they receive less attention from IT and are therefore less critical to the success of the audit in the first place? (I know, this is pretty weak logic. Cut me some slack, okay? :-) )

Posted by: Dave Taylor at February 1, 2005 3:39 AM

Hi,

I am enquiring about timing systems online. I am looking for a very accurate timing mechanism to incorporate into my website to evaluate correct
responses and the time it took to complete an exercise. This will be down to the millisecond. The timing mechanism should begin when the user
clicks a button and will end in the same way - at the push of an onscreen button. It would be great if the software could display a counter online as well. Any ideas on what I should go with?

Posted by: Damien at October 19, 2005 5:00 PM

Damien, pop over to Google and check out the results for "javascript millisecond timer". There are some interesting choices out there, and, yes, you can time down to the millisecond granularity.

Posted by: Dave Taylor at October 20, 2005 2:35 AM

hi
i have a problem , we are developing a online exam projects now how can we integrate a timer with this. like if our max time for exam is 30 min then after 30 min automatically it should stop the exam and declare the result

thanks

Posted by: dinesh at December 1, 2005 5:53 AM

thanks alot for the reply

Posted by: Jordan at May 18, 2006 11:53 AM

If you need one that works on myspace, check out this page Here

Posted by: Brad at February 15, 2007 9:56 PM

Hi
I Want To Set reminder In JSP Usingign JavaScript How I Set ??

Posted by: Ashish at March 16, 2007 1:31 AM

First of all I know nothing about html. I want to add the timer that you see if you go to the link below. I want to put that timer or create my own and put it on my Facebook profile. Is this possible and how? Thanks

Posted by: Joe at September 10, 2007 7:20 PM

hi
i have a problem , we are developing a online exam projects now how can we integrate a timer with this. like if our max time for exam is 30 min then after 30 min automatically it should stop the exam and declare the result

Posted by: zein at September 15, 2007 1:11 PM

I am looking to make a countdown clock for my webpage.... I don't have it published yet as I am not done with it...

Posted by: Lonnie Owens at January 12, 2008 12:46 PM

I want to send a mail automataically to a client afer 1 hour from my jsp page by using Javascript?

Posted by: madhu at January 17, 2008 10:26 AM

I am using your coutdown timer, however, instead of changing the date count each day at midnight it changes it at roughly noon. The only thing I changed in the code is the date we need it to count down to. Any advice on what I am doing wrong?

Posted by: Charles at February 20, 2008 3:08 PM

I have a lot to say, but ...
Starbucks coffee cup I have a lot to say, and questions of my own for that matter, but most of all I'd like to say thank you for all your efforts on this Web site by buying you a chai!

I do have a comment, now that you mention it!









Remember personal info?


Please note that I will never send you any unsolicited commercial email. Ever.

While I'm at it, please note that by submitting a question or comment you're agreeing to my terms of service, which are: you relinquish any subsequent rights of ownership to your material by submitting it on this site.









Search
Find just the answers you seek from among our 1700+ free tech support articles by using our Lijit search engine.


Help!





Subscribe to
Ask Dave Taylor!

Add to Google Reader
Add to My Yahoo!
Subscribe in NewsGator Online

RDF   XML

Free Updates!
Sign up and get free weekly updates and special offers on books, seminars, workshops and more.


Recent Entries
Join the List!
Join my author info mailing list, where you'll learn about my upcoming books, speaking gigs, and more!


Book Links
© 2002 - 2008 by Dave Taylor. All Rights Reserved.

Note: This web site is for the purpose of disseminating information for educational purposes, free of charge, for the benefit of all visitors. We take great care to provide quality information. However, we do not guarantee, and accept no legal liability whatsoever arising from or connected to, the accuracy, reliability, currency or completeness of any material contained on this web site or on any linked site.

[whiteboard marker tray]