Home >Web Front-end >JS Tutorial >Build a Countdown Timer in Just 18 Lines of JavaScript

Build a Countdown Timer in Just 18 Lines of JavaScript

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2025-02-10 10:59:10420browse

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:

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

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:

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

Convert time to available format

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.

  1. Divide milliseconds by 1000 to seconds: (t/1000)
  2. 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
  3. 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:

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

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:

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

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

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

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:

<code class="language-javascript">const deadline = '2015-12-31';</code>

Use the following:

<code class="language-javascript">const deadline = '31/12/2015';</code>

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

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:

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

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:

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

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

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:

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

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:

  1. If the deadline is recorded in the cookie, the deadline is used.
  2. 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:

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

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn