Robert Johns | 03 Apr, 2024
Fact checked by Jim Markus

How To Create A JavaScript Countdown Timer For Beginners

Want to know how to create a JavaScript countdown timer? In this tutorial, I’ll walk you through this JavaScript project step-by-step. 

Whether you’re just starting out in web development or want to learn JavaScript, this is a fantastic project for beginners to learn real-world JavaScript skills.

In this JavaScript tutorial, you’ll:

  • Design a User Interface for Your Countdown Timer.
  • Implement the JavaScript Logic for the Countdown Timer.
  • Connect the Timer Logic with the Display.
  • Handle Completion of the Countdown.

To make the most of this tutorial, it helps to have a basic understanding of web development, including familiarity with HTML and CSS. 

Some prior experience with JavaScript, such as manipulating HTML DOM elements and handling events, can be helpful. However, you don't need advanced knowledge of JavaScript or prior experience with countdown timers.

I’ve also provided the full source code for this JavaScript project so you can follow along, experiment, and even build upon it for your own projects. 

Plus, you can follow along with me using our online JavaScript compiler, so you don't need an IDE to code this JavaScript project from scratch.

Let’s dive in and start building!

How To Create a JavaScript Countdown Timer

Are you ready to dive into the exciting world of web development with a fun and interactive JavaScript project

Well, you're in the right place because today, we're going to learn how to create a JavaScript countdown timer with HTML, CSS, and JavaScript. 

If you’re new to JavaScript or web development, this project is a great way to understand how these three technologies come together to create dynamic and eye-catching websites.

At the heart of this project, I’ll show you how JavaScript can breathe life into a static webpage. 

I like to think of JavaScript as the puppeteer and HTML/CSS as the puppet. Together, they're going to put on quite a show! 

We'll use JavaScript to make our timer tick in real time, count down to a specific event, or just create a sense of urgency for a special sale on a website.

But it's not all about functionality; we're also going to make our timer look good. That's where CSS comes in, adding style, flair, and those cool modern aesthetics to our timer.

Take a look at the image I’ve included below to see what you’re going to be building!

Create your own JavaScript Countdown Timer

Now, you might be thinking, "Is this going to be hard?" 

Not at all! This JavaScript project is for beginners, and I’ll break it down into simple, digestible steps. 

Whether you're a beginner just getting your feet wet in web development or someone who's dabbled in HTML and CSS but hasn't explored much JavaScript, this project is perfect for you.

So, let's roll up our sleeves, fire up our favorite web development IDEs, and get ready to create something awesome. 

By the end of this, you'll not only have a cool Countdown Timer to show off in your portfolio but also a deeper understanding of how JavaScript works with HTML and CSS. 

Let's get started!

Project Prerequisites

Before we jump into the deep end of creating our JavaScript countdown timer, let's make sure we're all geared up with the right skills. 

Don't worry, you don't need to be a web development pro to get started, but having a few basics under your belt will make this journey smoother and more enjoyable.

And don’t worry if you're rusty in any of these areas, no stress! 

You can always brush up your skills with a JavaScript course. And remember, we’re here to help, so don’t hesitate to search on hackr.io for help with things up as you go along.

A Touch of HTML

HTML is the backbone of any website. It's like the framework of a house – essential and foundational. 

For this project, you should be comfortable with basic HTML tags (like <div>, <p>, <span>) and the structure of an HTML document. 

If you've ever created a simple webpage or played around with HTML at school or on a web development course, you're good to go!

Basic CSS Skills

CSS is what we use to make our web pages pretty. It's the interior design for our HTML house. Here, you should know how to style elements using CSS – things like setting colors, fonts, and basic layout properties (like margins and paddings). 

If you've ever found yourself playing with colors or aligning content on a page, you've got enough CSS knowledge for this project.

JavaScript Fundamentals

JavaScript is the magic that makes our page interactive. It's like adding smart home features to our HTML house. 

You don't need to be a JavaScript wizard, but you should understand basics like variables, functions, and event handling. 

If terms like function, event listener, or Date object don't sound too alien to you, you're all set! You can always refer to a JavaScript cheat sheet if you need a quick refresher.

A Curious and Experimental Mind 

This might be the most important prerequisite. The best way to learn is by doing, making mistakes, and trying again. 

Be ready to experiment, tweak the code, and maybe even break things (and then fix them). That's how we learn and grow!

You could also consider using an AI coding assistant like GitHub Copilot to help out, but I’d recommend waiting until you’re 100% stuck, as this is where you really learn.

Step 1: Setting Up The Project

Alright! Let's get our hands dirty and start setting up our project. This step is all about laying the groundwork for our Countdown Timer. 

If you want to dive straight in, I'd recommend following along with me using our online JavaScript compiler. This is pre-populated with the HTML, CSS, and JavaScript files you need to build this JavaScript project without switching on an IDE.

Alternatively, I've outlined the steps for you to create the necessary files and organize your workspace on your own computer. Just follow these, and you'll have a solid foundation for your project.

i. Create a Project Folder

First things first, let's keep things tidy. Create a new folder on your computer where you'll store all the files for this project. You can name it something like countdown-timer.

ii. Initialize Your Files

Inside your project folder, you're going to create three essential files:

  • index.html: This will be the main HTML file for your project.
  • style.css: This CSS file will hold all your styling rules to make your timer look snazzy.
  • script.js: Here's where the magic happens – your JavaScript code goes in this file.

You can create these files using a code editor like VSCode and Sublime Text or even a text editor like Notepad. Just make sure to save them with the correct extensions.

iii. Link Your CSS and JavaScript Files

Once you've created these files, you need to link them together. Open your index.html file and add the following lines of code inside the <head> tag for the CSS:

<link rel="stylesheet" href="style.css">

Try It Yourself »

And right before the closing </body> tag, add this line for the JavaScript:

<script src="script.js"></script>

Try It Yourself »

These lines tell your HTML file where to find the CSS and JavaScript files and incorporate them into your webpage.

iv. Open Your Project in a Browser

Now, let's see what we've got. Open your index.html file in a web browser. 

You won't see much yet – a blank page – but that's about to change. If the page opens without any errors, you're all set!

v. Ready Your Tools

As you work through the next steps, keep your code editor and web browser open side by side. This will allow you to make changes to your code and immediately see the results in the browser.

And there you have it! You've successfully set up your project, and you're ready to dive into the exciting part. 

Let's move on to Step 2, where we'll start crafting the HTML structure.

Step 2: Building The HTML Structure

With our project set up, it's time to lay the foundation with HTML. 

This step is all about creating the structure of our Countdown Timer. We'll define where each element of our timer will live on the webpage. Let's dive in!

i. Start with Basic HTML Skeleton

Open your index.html file. Here, we'll write the basic structure of an HTML document. If you're a bit rusty, don't worry – it's quite straightforward. Your file should look something like this:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Countdown Timer</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <!-- We'll add our timer elements here -->
  <script src="script.js"></script>
</body>
</html>

Try It Yourself »

This is the basic structure every HTML project and page starts with. We've got our DOCTYPE, HTML tag, head section (with meta tags, title, and link to our CSS file), and the body where our content will go.

ii. Adding the Timer Display

Inside the <body> tag, this is where we'll add the elements for our timer. We'll keep it simple yet functional:

<div id="countdown">
  <p id="timer">
      <span id="days"></span>
      <span class="timer-unit">Days</span>
      <span id="hours"></span>
      <span class="timer-unit">Hours</span>
      <span id="minutes"></span>
      <span class="timer-unit">Minutes</span>
      <span id="seconds"></span>
      <span class="timer-unit">Seconds</span>
  </p>
</div>

Try It Yourself »

Here's what we've done:

  • Created a div with the ID countdown. This is our main container for the timer.
  • Inside the div, we placed a p element with the ID timer.
  • We then added span elements for each time unit (days, hours, minutes, seconds) and their labels. The IDs (days, hours, minutes, seconds) will be used in our JavaScript to dynamically update the timer.

iii. Checking Your Work

Save your index.html file and refresh the page in your browser. You won't see anything yet because we haven't added any content or styles, but you're making sure there are no errors so far. If your page loads without issues, you're on the right track!

iv. Understanding the HTML Structure

  • The <!DOCTYPE html> declaration defines the document type and HTML version. It's essential for ensuring your webpage behaves correctly across different web browsers.
  • The <html lang="en"> tag sets the language of your document, which is important for accessibility and search engine optimization (SEO).
  • Inside the <head>, we have meta tags for character set and viewport settings, ensuring your site works well on mobile devices. The <title> gives your page a title, and the <link> tag connects your CSS file to style the page.
  • The <body> is where the visible part of your webpage lives. Here, we've started outlining our timer's structure, which will soon come to life with CSS and JavaScript.

v. Tips on Accessibility

While we're focusing on functionality and appearance, it's also good to keep accessibility in mind.

For instance, adding aria-label attributes to your timer elements can make it more accessible to users with screen readers. This might be a bit advanced for now, but it's something to keep in mind as you delve deeper into web development.

And voilà! You've successfully set up the basic HTML structure of your countdown timer. It might not look like much yet, but this is the skeleton upon which we'll build and dress up in the next steps. 

Great job getting this far – let's keep the momentum going as we move on to Step 3, where we'll add some style to our timer!

Step 3: Styling With CSS

Now our HTML skeleton is in place, it's time to dress it up with some CSS magic! 

This step is all about adding style to our Countdown Timer, transforming it from a mere structure to an eye-catching component on our webpage. 

Let's unleash our inner designer and get started!

i. Begin with Basic Styles

Open your style.css file. First, we'll set some basic styles to ensure our timer looks good on any device

body {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
  background: linear-gradient(135deg, #6dd5ed, #2193b0);
  color: white;
}

Try It Yourself »

Here's what we're doing:

  • Setting a universal font for consistency.
  • Using Flexbox to center our timer both vertically and horizontally.
  • Setting the height of the body to the full viewport height (100vh) for a full-screen effect.
  • Adding a cool gradient background for a modern look.
  • Setting the text color to white for contrast.

ii. Style the Countdown Timer

Now, let's focus on styling the countdown timer itself:

#countdown {
  background: rgba(0, 0, 0, 0.7);
  padding: 40px 60px;
  border-radius: 15px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
  text-align: center;
}

#timer {
  font-size: 3rem;
  letter-spacing: 3px;
}

.timer-unit {
  font-size: 1.2rem;
  text-transform: uppercase;
  letter-spacing: 2px;
  margin-top: 10px;
  display: block;
}

Try It Yourself »

In these styles, we're:

  • Using a semi-transparent background, padding, and rounded corners for a sleek look.
  • Adding a shadow for depth.
  • Setting font size, letter spacing, and typography properties to make the timer readable and stylish.

iii. Save and Refresh

After adding these styles, save your style.css file. Go back to your browser and refresh the page where you have index.html open. 

You should now see a beautiful timer layout, centered and styled, ready for the dynamic countdown functionality.

iv. Experiment with Styles

This is your canvas, so feel free to experiment with the styles. Change the font sizes, colors, background, or add any other CSS properties that catch your fancy. 

This experimentation is not just fun but also a great way to learn more about CSS and how it interacts with HTML elements. 

Remember, there's no right or wrong in design – it's all about what appeals to you and your audience.

v. Responsive Design Consideration

As a bonus challenge, try making your timer responsive. This means it should look good on devices of various sizes, from large desktop monitors to smaller mobile screens. 

You can use media queries in CSS to adjust styles based on the device's screen size. For example:

@media (max-width: 600px) {
  #timer {
      font-size: 2rem;
  }
  .timer-unit {
      font-size: 1rem;
  }
}

Try It Yourself »

This media query reduces the font size of the timer and its units on screens smaller than 600 pixels wide, making it more mobile-friendly.

And there you go! You've now added style to your timer, making it not just functional but also visually appealing. 

Great job on completing this step! Up next, we'll dive into the heart of our web development project – adding JavaScript to make our timer countdown to a specific event.

Step 4: JavaScript - Working With Dates

We're now venturing into the world of JavaScript to bring our countdown timer to life. In this step, we'll focus on working with dates, which is crucial for our timer functionality. 

We'll be setting our target date and getting familiar with JavaScript's Date object. Let's get coding!

i. Understanding the Date Object

Open your script.js file. JavaScript's Date object is a powerful tool for handling dates and times. To start, let's create a new Date object that represents the current date and time:

const currentDate = new Date();
console.log(currentDate); // This logs the current date and time to the console

Try It Yourself »

This line of code creates a new Date object and assigns it to the variable currentDate

If you open your browser's console, you'll see the current date and time printed out. It's a great way to verify that everything is working correctly.

If you’re not sure how to do this, you can typically access this via the browser development tools menu option or by using the F12 shortcut.

ii. Setting the Target Date

For our countdown timer, we need a target date to count down to. Let's set this up:

const targetDate = new Date('YYYY-MM-DDTHH:MM:SS'); // Replace with target
console.log(targetDate); // Check the target date in the console

Try It Yourself »

Replace 'YYYY-MM-DDTHH:MM:SS' with the actual date and time you want to count down to. 

Note that this follows the ISO 8601 standard, which is commonly used in JavaScript for date-time strings. Note the use of the T separator to distinguish between the date and time components.

So, we have a format of year-month-day and hour:minute:second. For example, 2024-12-31T23:59:59 would be the end of the year 2024.

iii. Calculating the Difference

To make our countdown work, we need to calculate the difference between the current date and the target date. 

We'll do this inside a JavaScript function that we'll write in the next steps. For now, understand that the difference will be calculated in milliseconds:

const difference = targetDate - currentDate;
console.log(difference); // This will log the difference in milliseconds

Try It Yourself »

This will give us the total number of milliseconds between the current date and the target date.

iv. Breaking Down the Difference

In the upcoming steps, we'll break down this difference into days, hours, minutes, and seconds, which will be displayed on our timer.

v. Testing Our Setup

After writing these lines of code, save your script.js file and refresh your browser. Make sure you see the correct current date, target date, and the calculated difference in the console. 

This step ensures that your date calculations are set up correctly before we move on to the actual countdown functionality.

Great job! You've now laid the groundwork for your countdown timer's functionality in JavaScript. In the next step, we'll dive deeper into the JavaScript code, creating the function that will update our countdown timer dynamically.

Step 5: JavaScript - Implementing Countdown Logic

It's time to get our Countdown Timer ticking! In this step, we'll implement the core functionality of our timer using JavaScript. 

We'll create a function that updates the countdown every second, bringing us closer to our target event. Let's dive into the heart of our project.

i. Creating the Update Function

Inside your script.js file, we're going to write a function named updateCountdown. This function will calculate the time remaining and update our HTML elements accordingly:

function updateCountdown() {
  const currentTime = new Date();
  const difference = targetDate - currentTime;

  const days = Math.floor(difference / (1000 * 60 * 60 * 24));
  const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((difference % (1000 * 60)) / 1000);

  document.getElementById("days").innerText = days;
  document.getElementById("hours").innerText = hours;
  document.getElementById("minutes").innerText = minutes;
  document.getElementById("seconds").innerText = seconds;
}

Try It Yourself »

Here's what's happening in this function:

  • We calculate the difference between the targetDate and currentTime.
  • We then break down this difference into days, hours, minutes, and seconds.
  • Each time unit is calculated by dividing the difference by the number of milliseconds in that unit.
  • Math.floor() is used to round down to the nearest whole number.
  • Finally, we update the HTML elements with these calculated values.

ii. Setting Up an Interval

To make our countdown update in real-time, we'll use setInterval to call our updateCountdown function every second:

const interval = setInterval(updateCountdown, 1000);

Try It Yourself »

  • setInterval() is a JavaScript function that calls a function or executes a code snippet repeatedly, with a fixed time delay between each call. Here, it's set to call updateCountdown every 1000 milliseconds (which is 1 second).
  • interval is a variable that stores the interval ID, which we can use to stop the interval later if needed.

iii. Handling the Countdown Completion

Inside our updateCountdown function, we need to handle what happens when the countdown reaches zero. We'll add a condition to stop the countdown and display a message:

if (difference < 0) {
  clearInterval(interval);
  document.getElementById("timer").innerText = "The event has started!";
}

Try It Yourself »

  • clearInterval(interval); stops the countdown when the target date is reached or passed.
  • We then update the timer element's text to indicate that the event has started.

iv. Testing the Countdown Timer

Save your script.js file and open (or refresh) your index.html in the browser. You should now see the countdown timer actively ticking down towards the target date and time.

v. Troubleshooting

If the timer isn't working as expected, here are a few things to check:

  • Ensure that your target date is correctly set in the future.
  • Check the console for any JavaScript errors.
  • Make sure that the IDs in your JavaScript match those in your HTML.

Congratulations! You've just implemented the core functionality of the countdown timer! 

This is a significant milestone, as you've combined JavaScript logic with dynamic HTML manipulation to create something interactive and useful. 

In the next steps, we'll finalize our project and test it thoroughly. Keep up the great work!

Step 6: JavaScript - Dynamically Updating HTML

Fantastic progress! Our countdown timer is ticking, but let's take it a notch higher. 

In this step, we're going to ensure our JavaScript is seamlessly updating the HTML elements in real time. 

This is what makes our timer interact with the user's browser, displaying the countdown as it happens. Let's jump into it!

i. Targeting HTML Elements with JavaScript

  • We've already written the code in our updateCountdown function to calculate the time units (days, hours, minutes, and seconds). Now, let's make sure these values are correctly displayed in the corresponding HTML elements.
  • Each time unit has its own <span> with a unique ID in our HTML. We use document.getElementById() in JavaScript to target these elements and update their content.

ii. Dynamic Content Update

Inside the updateCountdown function, after calculating the time units, we can add these lines:

document.getElementById("days").innerText = days;
document.getElementById("hours").innerText = hours;
document.getElementById("minutes").innerText = minutes;
document.getElementById("seconds").innerText = seconds;

Try It Yourself »

  • These lines dynamically update the content of the <span> elements for days, hours, minutes, and seconds.
  • innerText is a property that sets or returns the text content of the specified element. Here, it's used to display the countdown timer's current value.

iii. Testing Dynamic Updates

  • After adding these updates to your script, save the script.js file and refresh your browser.
  • Watch the countdown timer. You should see the numbers change in real time, accurately counting down to your target date.

iv. Ensuring Synchronization

  • It's important to ensure that the countdown updates at exactly one-second intervals to maintain accuracy. The setInterval method we've used is designed for this purpose, but it's always good to double-check.
  • Watch the timer for a minute or two to ensure it updates correctly and consistently.

v. Debugging

  • If the numbers aren't changing or you notice any irregularities, check the console in your web browser for any error messages.
  • Common issues might include typos in your JavaScript code, mismatched ID names between your HTML and JavaScript, or logical errors in the time calculations.

vi. Enhancing User Experience

Consider adding more feedback for the user when the countdown reaches zero, like changing the background color or displaying an animated effect. This can make the moment the countdown ends more exciting and noticeable.

vii. Code Optimization

Look over your code to see if there are any opportunities to make it more efficient or readable. For example, if you're repeating similar lines of code, you might be able to create a function to handle those repetitive tasks.

viii. Cross-Browser Testing

Finally, ensure that your countdown timer works well across different web browsers. Sometimes, different browsers may handle JavaScript and CSS differently, so it's good to test your timer in at least a couple of different browsers (like Chrome, Firefox, and Edge).

Congratulations! You've now successfully integrated dynamic HTML updates with JavaScript, a key skill in web development. 

Your countdown timer is not just a static display; it's a living, ticking clock on your webpage. 

Next, we'll wrap up our project and discuss some final touches and additional features you might consider. Great job on getting this far!

Step 7: JavaScript - Finalizing & Testing

We're almost at the finish line! In this step, we'll finalize our countdown timer, ensuring everything works smoothly and looks great.

We'll also go through some essential testing to make sure our timer is ready for the real world. Let's put the finishing touches on our JavaScript project.

i. Review the Complete Code

Take a moment to review your code in all three files (index.html, style.css, script.js). Ensure that everything is neat, well-commented, and organized. 

Clean code is easier to understand, debug, and maintain. Ensure that your CSS is consistent and that your JavaScript functions are working as intended.

ii. Test the Countdown Timer

  • Refresh your index.html page and observe the countdown timer. It should be accurately ticking down every second.
  • Check that the timer reaches zero at the correct target date and time and that it displays the end message ("The event has started!") appropriately.

iii. Responsiveness Check

  • Resize your browser window or test your page on different devices (like a smartphone or a tablet) to ensure that the timer is responsive and looks good on various screen sizes.
  • If there are any issues with how the timer looks on different devices, adjust your CSS accordingly. This might involve tweaking font sizes, padding, or layout properties using media queries.

iv. Troubleshoot Common Issues

  • If you encounter any problems, such as the timer not displaying correctly or not counting down as expected, go through your code again and look for any errors or typos.
  • Use the browser's developer tools to debug any issues. The console can be particularly helpful for identifying JavaScript errors.

v. User Experience Enhancements

  • Consider adding additional features for a better user experience, such as a message that changes as the event gets closer or an animation that triggers when the countdown completes.
  • Ensure that all user feedback is clear and understandable. For example, if the timer is for an event happening in a different time zone, consider displaying that information.

vi. Final Validation

  • Validate your HTML and CSS using online validation tools to ensure that they follow the current web standards. This is crucial for cross-browser compatibility and overall performance.
  • Check for any accessibility issues, like proper contrast ratios and screen reader compatibility, to make your timer inclusive for all users.

vii. Gather Feedback

  • If possible, get someone else to test your timer. A fresh pair of eyes can often spot issues you have missed.
  • Ask for feedback on both functionality and design and be open to making improvements based on this feedback.

Nice work! You've now completed all the essential steps for building and testing your Countdown Timer. 

You've not only created a functional web component but also ensured it's robust, responsive, and user-friendly. 

We'll now discuss next steps and how you can build on this project for future learning and development.

Next Steps & Further Learning

Bravo! You've successfully built a dynamic JavaScript countdown timer, and it looks fantastic. But the journey doesn't end here. 

Let's explore some next steps and ideas for further learning to keep your web development skills growing. 

The world of JavaScript is vast, and there's always something new and exciting to learn!

Add New Features

  • Customization Options: Allow users to set their own target date and time, perhaps through a user interface with input fields.
  • Time Zone Support: Enhance your timer to handle different time zones, making it useful for a global audience.
  • Visual Countdown: Create a graphical representation of the countdown, like a circular progress bar that depletes as time passes.
  • Sound and Alerts: Add an option for an alarm or sound effect when the countdown reaches zero.

Refine and Refactor

  • Code Optimization: Look for ways to make your code more efficient and streamlined. Can any parts be rewritten to be cleaner or faster?
  • Design Improvements: Experiment with different design elements. Try new color schemes, fonts, or layout changes to enhance the visual appeal.
  • Cross-Browser Testing: Make sure your timer works seamlessly across all major browsers and fix any compatibility issues.

Learn More About JavaScript and Web Technologies

  • Explore JavaScript Frameworks: Dive into JavaScript frameworks like React, Angular, or Vue.js. These tools can help you build more complex and interactive web applications.
  • Responsive Design Techniques: Learn more about creating responsive web designs that adapt to different screen sizes and devices.
  • Web Performance: Understand how to make your web applications faster and more efficient.

Join Online Communities and Collaborate

Engage with other developers through forums, social media groups, or local meetups. Collaboration and community involvement are great ways to learn and grow. You can also become part of the hackr.io community, we’d love to have you!

Keep Up with Trends and Best Practices

Web development and JavaScript are always evolving, so stay current by following blogs, attending webinars, and participating in online courses.

Document and Share Your Learning Journey

Consider blogging about your project or sharing it on platforms like GitHub. Documenting your process and sharing it with others can be a rewarding experience, not to mention a great way to get feedback or to make new network connections.

Challenge Yourself Regularly

Participate in coding challenges or hackathons. These can be great opportunities to push your limits and learn new things.

And if you're hungry for more JavaScript projects, check out the rest of our step-by-step tutorials, including:

You've taken a significant step in your web development journey by completing this JavaScript project. Plus, you now have something tangible to add to your portfolio. 

Remember, every expert was once a beginner. Keep building, keep experimenting, and most importantly, have fun with it! The world of web development is your oyster. 

JavaScript Countdown Timer Full Source Code

Now you’ve followed the steps above, your finished source code files should look like these I’ve included below.

Equally, if you’ve found yourself getting stuck at any point, take a look at these files for some help. 

HTML Source Code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Countdown Timer</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div id="countdown">
      <p id="timer">
          <span id="days"></span>
          <span class="timer-unit">Days</span>
          <span id="hours"></span>
          <span class="timer-unit">Hours</span>
          <span id="minutes"></span>
          <span class="timer-unit">Minutes</span>
          <span id="seconds"></span>
          <span class="timer-unit">Seconds</span>
      </p>
  </div>
  <script src="script.js"></script>
</body>
</html>

Try It Yourself »

CSS Source Code:

body {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
  background: linear-gradient(135deg, #6dd5ed, #2193b0);
  color: white;
}

#countdown {
  background: rgba(0, 0, 0, 0.7);
  padding: 40px 60px;
  border-radius: 15px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
  text-align: center;
}

#timer {
  font-size: 3rem;
  letter-spacing: 3px;
}

.timer-unit {
  font-size: 1.2rem;
  text-transform: uppercase;
  letter-spacing: 2px;
  margin-top: 10px;
  display: inline;
}

Try It Yourself »

JavaScript Source Code:

const targetDate = new Date('YYYY-MM-DDTHH:MM:SS'); // Set your target

function updateCountdown() {
  const currentTime = new Date();
  const difference = targetDate - currentTime;

  const days = Math.floor(difference / (1000 * 60 * 60 * 24));
  const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((difference % (1000 * 60)) / 1000);

  document.getElementById("days").innerText = days;
  document.getElementById("hours").innerText = hours;
  document.getElementById("minutes").innerText = minutes;
  document.getElementById("seconds").innerText = seconds;

  if (difference < 0) {
      clearInterval(interval);
      document.getElementById("timer").innerText = "The event has started!";
  }
}

const interval = setInterval(updateCountdown, 1000);

Try It Yourself »

Wrapping Up

Building a JavaScript countdown timer using HTML, CSS, and JavaScript is an excellent way to enhance your web development skills, explore new techniques, and delve into the world of dynamic web applications. 

By developing this JavaScript countdown timer, you've tackled various challenges, including crafting an engaging user interface, implementing real-time logic in JavaScript, and dynamically updating the webpage based on the timer's state.

In this tutorial, you’ve learned how to:

  • Use HTML and CSS to design a visually appealing layout for your Countdown Timer.
  • Write JavaScript to implement the logic of the countdown, accurately tracking time until a specified event.
  • Dynamically update HTML content with JavaScript, ensuring your timer reflects real-time changes.
  • Handle the completion of the countdown, providing feedback and options to the user once the target time is reached.

You now possess the tools and knowledge to further enhance this JavaScript countdown timer, including adding features like user input to set the target time, incorporating sound effects, or even integrating it into a larger web application. 

The skills you've honed here also lay a foundation for building other interactive web elements and applications.

Your journey in web development doesn't end here. With these new skills, you're well-equipped to experiment with more complex JavaScript projects, explore other aspects of JavaScript, and continue crafting engaging interactive web experiences.

And remember, you can do all this using our online JavaScript compiler, so get creative, have fun, and happy coding!

Want to sharpen up your JavaScript and web development skills? Check out:

Dr. Angela Yu's Complete Web Development Bootcamp

By Robert Johns

Technical Editor for Hackr.io | 15+ Years in Python, Java, SQL, C++, C#, JavaScript, Ruby, PHP, .NET, MATLAB, HTML & CSS, and more... 10+ Years in Networking, Cloud, APIs, Linux | 5+ Years in Data Science | 2x PhDs in Structural & Blast Engineering

View all post by the author

Subscribe to our Newsletter for Articles, News, & Jobs.

Thanks for subscribing! Look out for our welcome email to verify your email and get our free newsletters.

Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.

In this article

Learn More

Please login to leave comments