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:
- Code lightweight, zero dependency.
- The website performs better without loading external scripts and stylesheets.
- With more control, you can precisely control the behavior of the clock without trying to bending the plug-in to suit your needs.
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".
Key Points
- You can build a lightweight and efficient countdown clock using JavaScript without any dependencies, providing better performance and control without loading external scripts and stylesheets.
- This process includes setting a valid end date, calculating the remaining time, converting the time into available formats, outputting the clock data as a reusable object, and displaying the clock on the page and stopping it when zero is reached.
- You can optimize clock display by removing the initial delay, updating only the numbers in the clock to improve scripting efficiency, and adding leading zeros as needed.
- For some use cases, clocks can be extended, such as automatically scheduling the clock, setting a timer for a specific time when a user arrives, and maintaining clock progress across pages by saving the end time of the clock in a cookie.
- One important warning to remember: JavaScript dates and times are taken from the user's computer, which means that users can affect the JavaScript clock by changing the time on their computer. In extremely sensitive situations, it may be necessary to obtain time from the server.
Basic Clock: Countdown to a specific date or time
Creating a basic clock involves the following steps:
- Set the valid end date.
- Calculate the remaining time.
- Convert time to available format.
- Output clock data as a reusable object.
- Displays the clock on the page and stops the clock when zero is reached.
Set valid end date
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:
const deadline = '2015-12-31';
Short format:
const deadline = '31/12/2015';
or long format:
const deadline = 'December 31 2015';
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:
const deadline = 'December 31 2015 23:59:59 GMT+0200';
You can read more about JavaScript date format in this article.
Calculate the remaining time
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:
const deadline = '2015-12-31';
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.
const deadline = '31/12/2015';
Convert time to available format
Now we want to convert milliseconds into days, hours, minutes and seconds. Let's take seconds as an example:
const deadline = 'December 31 2015';
Let's break down what's going on here.
- Divide milliseconds by 1000 to seconds: (t/1000)
- Divide the total number of seconds by 60 and get the remainder. You don't need all the seconds, you just need to calculate the remaining seconds after the minute: (t/1000) % 60
- Round it to the nearest integer. This is because you need the full number of seconds, not the fractional part of the second:
Math.floor( (t/1000) % 60 )
Repeat this logic to convert milliseconds into minutes, hours, and days.
Output clock data as a reusable object
When we prepare the days, hours, minutes and seconds, we can now return the data as a reusable object:
const deadline = 'December 31 2015 23:59:59 GMT+0200';
This object allows you to call your function and get any calculated value. Here is an example of how to get the remaining minutes:
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 }; }
Is it convenient?
Show the clock and stop it when it reaches zero
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:
const total = Date.parse(endtime) - Date.parse(new Date());
Then we will write a function that outputs clock data to our new div:
const seconds = Math.floor( (t/1000) % 60 );
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:
- Calculate the remaining time.
- Output the remaining time to our div.
- If the remaining time reaches zero, stop the clock.
At this point, the only remaining step is to run the clock, as shown below:
return { total, days, hours, minutes, seconds };
Congratulations! You now have only 18 lines of JavaScript code to have a basic clock.
Prepare to display your clock
We need to improve a little bit before setting the clock style.
- Remove the initial delay so that your clock will be displayed immediately.
- Make the clock script more efficient so that it does not rebuild the entire clock continuously.
- Add leading zeros as needed.
Delete the initial delay
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:
const deadline = '2015-12-31';
Use the following:
const deadline = '31/12/2015';
Avoid continuous rebuilding of clocks
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>
tag and update only those <span>
contents.
This is HTML:
const deadline = 'December 31 2015';
Let us now get a reference to these elements. Add the following code after defining the clock
variable
const deadline = 'December 31 2015 23:59:59 GMT+0200';
Next, we need to change the updateClock
function to update only the numbers. The new code will look like this:
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 }; }
Add leading zeros
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:
const total = Date.parse(endtime) - Date.parse(new Date());
For this:
const seconds = Math.floor( (t/1000) % 60 );
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.
Go a step further
The following example demonstrates how to scale the clock for some use cases. They are all based on the basic examples seen above.
Automatically schedule the clock
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:
return { total, days, hours, minutes, seconds };
Next, we can specify the date range that the clock should display. This will replace the deadline
variable:
const deadline = '2015-12-31';
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.
const deadline = '31/12/2015';
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.
Set a 10-minute timer when the user arrives
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:
const deadline = 'December 31 2015';
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.
Clock progress across pages
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:
- If the deadline is recorded in the cookie, the deadline is used.
- If the cookie does not exist, a new deadline is set and stored in the cookie.
To achieve this, replace the deadline
variable with the following:
const deadline = 'December 31 2015 23:59:59 GMT+0200';
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.
Another important warning about client time
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.
Summary
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.
Next steps
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.
Frequently Asked Questions about Using Time and Date in JavaScript
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...
