Home >Web Front-end >JS Tutorial >Build a Countdown Timer in Just 18 Lines of JavaScript
Building a JavaScript countdown clock is sometimes necessary, whether it is an event, a promotion or a game. You can build the clock using native JavaScript without relying on any plugins. Although there are many excellent clock plugins, using native JavaScript has the following advantages:
Here is how to create your own countdown clock with just 18 lines of JavaScript code:
To gain an in-depth understanding of JavaScript, please read our book "JavaScript: Novice to Ninja, 2nd Edition".
Creating a basic clock involves the following steps:
First, you need to set a valid end date. This should be a string that can be understood in any format using JavaScript's Date.parse()
method. For example:
ISO 8601 format:
<code class="language-javascript">const deadline = '2015-12-31';</code>
Short format:
<code class="language-javascript">const deadline = '31/12/2015';</code>
or long format:
<code class="language-javascript">const deadline = 'December 31 2015';</code>
Each format allows you to specify the exact time and time zone (or specify the offset from UTC in the case of an ISO date). For example:
<code class="language-javascript">const deadline = 'December 31 2015 23:59:59 GMT+0200';</code>
You can read more about JavaScript date format in this article.
The next step is to calculate the remaining time. We need to write a function that accepts a string representing a given end time (as described above). We then calculate the difference between that time and the current time. As shown below:
<code class="language-javascript">const deadline = '2015-12-31';</code>
First, we create a variable total
to save the remaining time before the deadline. The Date.parse()
function converts a time string to a value in milliseconds. This allows us to subtract two times from each other and get the amount of time between the two.
<code class="language-javascript">const deadline = '31/12/2015';</code>
Now we want to convert milliseconds into days, hours, minutes and seconds. Let's take seconds as an example:
<code class="language-javascript">const deadline = 'December 31 2015';</code>
Let's break down what's going on here.
Math.floor( (t/1000) % 60 )
Repeat this logic to convert milliseconds into minutes, hours, and days.
When we prepare the days, hours, minutes and seconds, we can now return the data as a reusable object:
<code class="language-javascript">const deadline = 'December 31 2015 23:59:59 GMT+0200';</code>
This object allows you to call your function and get any calculated value. Here is an example of how to get the remaining minutes:
<code class="language-javascript">function getTimeRemaining(endtime){ const total = Date.parse(endtime) - Date.parse(new Date()); const seconds = Math.floor( (total/1000) % 60 ); const minutes = Math.floor( (total/1000/60) % 60 ); const hours = Math.floor( (total/(1000*60*60)) % 24 ); const days = Math.floor( total/(1000*60*60*24) ); return { total, days, hours, minutes, seconds }; }</code>
Is it convenient?
Now we have a function that outputs the remaining days, hours, minutes, and seconds, and we can build our clock. First, we will create the following HTML element to save our clock:
<code class="language-javascript">const total = Date.parse(endtime) - Date.parse(new Date());</code>
Then we will write a function that outputs clock data to our new div:
<code class="language-javascript">const seconds = Math.floor( (t/1000) % 60 );</code>
This function takes two parameters. They are the id of the element that contains our clock and the end time of the countdown. Inside the function, we will declare a clock
variable and use it to store a reference to our clock container div. This means we don't have to keep querying the DOM.
Next, we will execute an anonymous function per second using setInterval
. This function will do the following:
At this point, the only remaining step is to run the clock, as shown below:
<code class="language-javascript">return { total, days, hours, minutes, seconds };</code>
Congratulations! You now have only 18 lines of JavaScript code to have a basic clock.
We need to improve a little bit before setting the clock style.
In the clock, we use setInterval
to update the display every second. This is OK in most cases, but at the beginning, there will be a second delay. To remove this delay, we must update the clock once before the interval begins.
Let's move the anonymous function passed to setInterval
into its own separate function. We can name this function updateClock
. Call the setInterval
function once outside updateClock
and call it again inside setInterval
. In this way, the clock will be displayed without delay.
In your JavaScript, replace the following:
<code class="language-javascript">const deadline = '2015-12-31';</code>
Use the following:
<code class="language-javascript">const deadline = '31/12/2015';</code>
We need to make clock scripts more efficient. We want to update only the numbers in the clock, rather than rebuilding the entire clock every second. One way to do this is to put each number inside a <span></span>
tag and update only those <span></span>
contents.
This is HTML:
<code class="language-javascript">const deadline = 'December 31 2015';</code>
Let us now get a reference to these elements. Add the following code after defining the clock
variable
<code class="language-javascript">const deadline = 'December 31 2015 23:59:59 GMT+0200';</code>
Next, we need to change the updateClock
function to update only the numbers. The new code will look like this:
<code class="language-javascript">function getTimeRemaining(endtime){ const total = Date.parse(endtime) - Date.parse(new Date()); const seconds = Math.floor( (total/1000) % 60 ); const minutes = Math.floor( (total/1000/60) % 60 ); const hours = Math.floor( (total/(1000*60*60)) % 24 ); const days = Math.floor( total/(1000*60*60*24) ); return { total, days, hours, minutes, seconds }; }</code>
Now that the clock is no longer rebuilding every second, we have one more thing to do: add leading zeros. For example, the clock does not display 7 seconds, but displays 07 seconds. An easy way is to add a "0" string at the beginning of the number and then cut off the last two digits.
For example, to add leading zeros to the "seconds" value, you will change the following:
<code class="language-javascript">const total = Date.parse(endtime) - Date.parse(new Date());</code>
For this:
<code class="language-javascript">const seconds = Math.floor( (t/1000) % 60 );</code>
You can also add leading zeros to minutes and hours if you prefer. If you have come this far, congratulations! Your clock is now available to display.
Note: You may need to click "Rerun" in CodePen to start the countdown.
The following example demonstrates how to scale the clock for some use cases. They are all based on the basic examples seen above.
Suppose we want the clock to be displayed on some days and not on other days. For example, we may have a series of upcoming events and don't want to manually update the clock every time. Here is how to arrange things in advance.
Hide the clock by setting the display
property of the clock to none
. Then add the following to the initializeClock
function (after the line starting with var clock
). This will cause the clock to appear only after calling the initializeClock
function:
<code class="language-javascript">return { total, days, hours, minutes, seconds };</code>
Next, we can specify the date range that the clock should display. This will replace the deadline
variable:
<code class="language-javascript">const deadline = '2015-12-31';</code>
schedule
Each element in the array represents a start date and an end date. As mentioned above, time and time zones can be included, but I'm using normal dates here to keep the code readable.
Finally, when the user loads the page, we need to check if we are within any specified time range. This code should replace the previous call to the initializeClock
function.
<code class="language-javascript">const deadline = '31/12/2015';</code>
Now you can schedule the clock in advance without manually updating it. You can shorten the code as needed. For readability, I make my code verbose.
It 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 10-minute timer here, but you can use whatever amount of time you want.
We just need to replace the deadline
variable with the following:
<code class="language-javascript">const deadline = 'December 31 2015';</code>
This code gets the current time and adds ten minutes. The values are converted to milliseconds, so they can be added together and converted to a new deadline.
Now we have a clock that counts down ten minutes from when the user arrives. Feel free to try different lengths of time.
Sometimes it is necessary to save the state of the clock, not just the current page. If we want to set a 10-minute timer across the entire website, we don't want it to reset when the user goes to a different page.
One solution is to save the end time of the clock in the cookie. This way, navigating to the new page does not reset the end time to ten minutes from now.
This is the logic:
To achieve this, replace the deadline
variable with the following:
<code class="language-javascript">const deadline = 'December 31 2015 23:59:59 GMT+0200';</code>
This code uses cookies and regular expressions, both of which are separate topics. Therefore, I will not go into details here. One thing to note is that you need to change .yourdomain.com
to your actual domain name.
JavaScript date and time are taken from the user's computer. This means that users can affect the JavaScript clock by changing the time on their computer. In most cases, this doesn't matter. But in some extremely sensitive situations, time is required to be obtained from the server. This can be done with some PHP or Ajax, which is beyond the scope of this tutorial.
After getting time from the server, we can use the same techniques in this tutorial to handle it.
After completing the examples in this article, you now know how to create your own countdown timer with just a small amount of native JavaScript code! We've learned how to make a basic countdown clock and display it efficiently. We also covered some useful additional features including scheduling, absolute versus relative time, and the use of cookies to save state between page and website access.
Try using your clock code. Try adding some creative styles or new features (such as pause and restore buttons). After that, if you want to share any cool clock examples, let us know in the forum.
How to get the current date and time in JavaScript? You can use the Date
object to get the current date and time. Simply create a new instance of Date
without parameters, which will represent the current date and time.
What are the common date and time operations in JavaScript? Common operations include formatting dates, parsing date strings, calculating time intervals, adding or subtracting time, and comparing dates.
What is the recommended way to deal with time zones in JavaScript? It is best to use UTC time as much as possible to avoid time zone problems. When displaying time to the user, consider using the toLocaleString
method and using the timeZone
option to specify the desired time zone.
How to calculate the difference between two dates in JavaScript? You can subtract two Date
objects to get time intervals in milliseconds and convert them to days, hours, minutes, etc. using math operations.
Can I easily manipulate dates in JavaScript? Yes, JavaScript provides some ways to add and subtract time intervals to dates. The Date
object has methods such as setFullYear
, setMonth
, setDate
, etc., which are used for date operations.
The above is the detailed content of Build a Countdown Timer in Just 18 Lines of JavaScript. For more information, please follow other related articles on the PHP Chinese website!