亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Key Points
Basic Clock: Countdown to a specific date or time
Set valid end date
Calculate the remaining time
Convert time to available format
Output clock data as a reusable object
Show the clock and stop it when it reaches zero
Prepare to display your clock
Delete the initial delay
Avoid continuous rebuilding of clocks
Add leading zeros
Go a step further
Automatically schedule the clock
Set a 10-minute timer when the user arrives
Clock progress across pages
Another important warning about client time
Summary
Next steps
Frequently Asked Questions about Using Time and Date in JavaScript
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

Feb 10, 2025 am 10:59 AM

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.

  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:

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

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.

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:

  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:

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!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

A definitive JS roundup on JavaScript modules: ES Modules vs CommonJS A definitive JS roundup on JavaScript modules: ES Modules vs CommonJS Jul 02, 2025 am 01:28 AM

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.

How does garbage collection work in JavaScript? How does garbage collection work in JavaScript? Jul 04, 2025 am 12:42 AM

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

How to make an HTTP request in Node.js? How to make an HTTP request in Node.js? Jul 13, 2025 am 02:18 AM

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

var vs let vs const: a quick JS roundup explainer var vs let vs const: a quick JS roundup explainer Jul 02, 2025 am 01:18 AM

The difference between var, let and const is scope, promotion and repeated declarations. 1.var is the function scope, with variable promotion, allowing repeated declarations; 2.let is the block-level scope, with temporary dead zones, and repeated declarations are not allowed; 3.const is also the block-level scope, and must be assigned immediately, and cannot be reassigned, but the internal value of the reference type can be modified. Use const first, use let when changing variables, and avoid using var.

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

How to traverse the DOM tree (e.g., parentNode, children, nextElementSibling)? How to traverse the DOM tree (e.g., parentNode, children, nextElementSibling)? Jul 02, 2025 am 12:39 AM

DOM traversal is the basis of web page element operation. Common methods include: 1. Use parentNode to obtain the parent node, and can be chained to find it upward; 2. children return a collection of child elements, accessing the first or end child elements through the index; 3. nextElementSibling obtains the next sibling element, and combines previousElementSibling to realize the same-level navigation. Practical applications such as dynamically modifying structures, interactive effects, etc., such as clicking the button to highlight the next brother node. After mastering these methods, complex operations can be achieved through combination.

See all articles