Sometimes, you’re going to need to build a JavaScript countdown clock. You may have an event, a sale, a promotion, or a game. You can build 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: Show
So, without further ado, here’s how to make your own countdown clock in a mere 18 lines of JavaScript. For in-depth JavaScript knowledge, read our book, JavaScript: Novice to Ninja, 2nd Edition. Basic Clock: Count down to a Specific Date or TimeHere’s a quick outline of the steps involved in creating a basic clock:
Set a Valid End DateFirst, 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:
The short format:
Or, the long format:
Each of these formats allows you to specify an exact time and a time zone (or an offset from UTC in the case of ISO dates). For example:
You can read more about date formatting in JavaScript in this article. Calculate the Time RemainingThe next step is to calculate the time remaining. We need to write a function that takes a string representing a given end time (as outlined above). We then calculate the difference between that time and the current time. Here’s what that looks like:
First, we’re creating a variable
Convert the Time to a Usable FormatNow we want to convert the milliseconds to days, hours, minutes, and seconds. Let’s use seconds as an example:
Let’s break down what’s going on here.
Repeat this logic to convert the milliseconds to minutes, hours, and days. Output the Clock Data as a Reusable ObjectWith the days, hours, minutes, and seconds prepared, we’re now ready to return the data as a reusable object:
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 ZeroNow 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:
Then we’ll write a function that outputs the clock data inside our new div:
This function takes two parameters. These are the id of the element that contains our clock, and the
countdown’s end time. Inside the function, we’ll declare a Next, we’ll use
At this point, the only remaining step is to run the clock like so:
Congratulations! You now have a basic clock in just 18 lines of JavaScript. Prepare Your Clock for DisplayBefore styling the clock, we’ll need to refine things a little.
Remove the Initial DelayIn the clock, we’ve used Let’s move the anonymous function that we’re passing to In your JavaScript, replace this:
With this:
Avoid Continuously Rebuilding the ClockWe need 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 Here’s the HTML:
Now let’s get a reference to those elements. Add the following code right after where the
Next, we need to alter the
Add Leading ZerosNow that the clock is no longer 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:
to this:
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 Taking it FurtherThe 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 AutomaticallyLet’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
Next we can specify the dates between which the clock should show up. This will replace the
Each element in the 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
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. Set Timer for 10 Minutes from When the User ArrivesIt may be necessary to set a countdown for a given amount of time after the user arrives or starts a specific task. We’ll set a timer for 10 minutes here, but you can use any amount of time you want. All we need to do here is replace the
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 PagesSometimes it’s necessary to preserve the state of the clock for more than just the current page. If we wanted to set a 10-minute timer across the site, we wouldn’t want it to reset when the user goes to a different page. 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:
To implement this, replace the
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 An Important Caveat about Client-Side TimeJavaScript 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. After getting the time from the server, we can work with it using the same techniques from this tutorial. Summing UpAfter working through the examples in this article, you now know how to create your own countdown timer with just a handful of lines of vanilla JavaScript code! We’ve looked at how to make a basic countdown clock and display it efficiently. We’ve also covered adding some useful additional functionality, including scheduling, absolute versus relative times, and preserving state between pages and site visits with cookies. What’s Next?Play around with your clock code. Try adding some creative styles, or new features (such as pause and resume buttons). After that, if you come up with any cool clock examples you’d like to share, let us know on the forums. How do you make a countdown timer?Creating countdown timers. Click Create…. The Create Countdown Timer window opens.. You can make the following settings: Name. Enter a name for your countdown timer. ... . Click Save.. Click Close. The Countdown Timer window opens. If you select a created countdown timer from the list, a preview of the countdown timer is shown.. How do I put a countdown clock on my website?How to add Countdown Timer to a website. Customize the widget. Use diverse options to get a perfect for your use-case widget.. Get your installation code. Get the unique code for your customized widget and copy it.. Paste the code into your website. Paste the code into the desired place of the website or template.. Does JavaScript have a timer function?There are two timer functions in JavaScript: setTimeout() and setInterval() . The following section will show you how to create timers to delay code execution as well as how to perform one or more actions repeatedly using these functions in JavaScript.
How do you add a time counter in HTML?Display the clock on the page, and stop the clock when it reaches zero.. Step 1 : Set a Valid End Date. The Valid end date and time should be a string in any of the formats understood by JavaScript's Date. ... . Step 2 : Calculate Remaining Time. ... . Step 3 : Output the result. ... . Step 4 : Write some text if the countdown is over.. What is timer in JavaScript?In JavaScript, a timer is created to execute a task or any function at a particular time. Basically, the timer is used to delay the execution of the program or to execute the JavaScript code in a regular time interval. With the help of timer, we can delay the execution of the code.
|