How to create a countdown timer using JavaScript

Key takeaways:

  • JavaScript offers two main functions for handling timed operations:

    • setInterval(): This function executes a specified function at fixed intervals, which is perfect for creating a real-time countdown.

    • setTimeout(): This function runs a specified function only once after a given delay, ideal for a single action.

  • Both methods are useful in various scenarios, each with unique properties and best use cases.

Imagine a web app displaying a countdown timer for special events, like product launches, sale announcements, or even personal goals! Countdown timers are fun and practical, adding an engaging element to the webpage. JavaScript provides two powerful methods for working with time-based functions: setTimeout() and setInterval(). In this Answer, we’ll walk through creating a countdown timer using JavaScript, explaining each line of code so we can understand the process together.

Setting up the countdown timer

The setInterval() and setTimeout() methods are built-in JavaScript functions used to manage time-based operations in web applications. They allow us to run functions after specific delays (setTimeout()) or repeatedly at fixed intervals (setInterval()). Let’s dive in and start building our countdown timer with both methods.

Step 1: HTML structure

First, we’ll set up our HTML to display the countdown timer. This will contain an element to show the remaining time.

<!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>
</head>
<body>
<h1>Event Countdown Timer</h1>
<div id="countdown"></div>
<script src="script.js"></script>
</body>
</html>
A basic HTML structure for the countdown timer

In the HTML code:

  • Line 10: We create a <div> element with the ID countdown, where the timer will be displayed.

  • Line 12: We include an external JavaScript file, script.js, which will contain the countdown timer logic.

Step 2: JavaScript logic using the setInterval() method

With the HTML structure ready, let’s now focus on the JavaScript code in script.js. Here, we’ll:

  1. Set a target date.

  2. Use JavaScript’s setInterval() method to update the timer every second. The setInterval() function is used to repeatedly execute a function or a code snippet at specified intervals. It keeps running the function until it’s stopped.

  3. Display the remaining time in days, hours, minutes, and seconds.

// Set the countdown end date and time
const targetDate = new Date("December 31, 2024 23:59:59").getTime();
// Update the countdown every second
const countdownInterval = setInterval(() => {
const now = new Date().getTime();
const timeLeft = targetDate - now;
// Calculate days, hours, minutes, and seconds
const days = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
const hours = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);
// Display the result in the countdown div
document.getElementById("countdown").innerHTML =
`${days}d ${hours}h ${minutes}m ${seconds}s`;
// Check if the countdown has ended
if (timeLeft < 0) {
clearInterval(countdownInterval);
document.getElementById("countdown").innerHTML = "The event has started!";
}
}, 1000);
A JavaScript logic using the setInterval() method for the countdown timer

In this JavaScript code:

  • Line 2: We set a target date by creating a new Date object with the desired date and time. We can set any desired time for the countdown timer.

  • Line 5: We use setInterval() to execute a function every second (1000 milliseconds).

  • Line 6: We get the current date and time with new Date().getTime().

  • Line 7: We calculate timeLeft by subtracting the current time (now) from the target time (targetDate).

  • Line 10: We calculate the days remaining by dividing timeLeft by the total milliseconds in a day.

  • Line 11: For hours, we use the modulus operator % to get the remaining time after subtracting days and dividing by the milliseconds in an hour.

  • Line 12: For minutes, we use % again to get the remaining time after hours and divide by the milliseconds in a minute.

  • Line 13: Finally, we calculate seconds using % and divide by 1000 (milliseconds in a second).

  • Lines 16–17: We display the countdown by updating the innerHTML of the countdown element with the calculated time.

  • Lines 20–23: Check if the countdown has ended by verifying if timeLeft is less than 0. If so, we stop the countdown using clearInterval and display a message indicating the event has started.

Step 3: Adding some style (optional)

To make the countdown timer look more attractive, let’s add a little CSS styling. Add this to a <style> tag in the HTML head section.

<style>
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f3f4f6;
color: #333;
}
#countdown {
font-size: 2em;
margin-top: 20px;
}
</style>
Adding some CSS styling to the HTML for the countdown timer

In this CSS file:

  • Lines 2–7: We center the text and style the font and background color.

  • Lines 8–11: We increase the font size of the countdown display for better visibility.

Application demo

Now, let’s run the application. For the demo, we set the targetDate for one minute. The countdown timer should display, updating every second until it reaches zero. Once the countdown is over, the message “The event has started!” will appear.

  • HTML
  • CSS
  • JavaScript
Countdown timer using the setInterval() method

Updating JavaScript logic using the setTimeout() method

The setTimeout() function is used to execute a function or a code snippet after a specified amount of time has passed. It triggers the function only once unless it’s called again.

Let’s add the JavaScript code in script.js:

  • HTML
  • CSS
  • JavaScript
Countdown timer using the setTimeout() method

In this JavaScript code:

  • Lines 6–26: We define the updateCountdown() function, which we’ll call every second to update the timer. Inside the timer, the logic of calculating the remaining time and displaying it remains the same. We update the following logic:

    • Lines 21–22: We check if timeLeft is greater than zero, we call the setTimeout(updateCountdown, 1000), which schedules the updateCountdown() function to run again after one second.

    • Lines 23–25: If the countdown has ended, we display a message that the event has started.

  • Line 29: We make an initial call to the updateCountdown() function to start the countdown timer.

Key differences between setTimeout() and setInterval()

Here’s a quick comparison of the two methods:

Feature

setTimeout()

setInterval()

Executes function

Once after the delay

Repeatedly at regular intervals

Common use cases

Delayed operations, notifications

Real-time clocks, live data updates

Overlapping risk

None

Potential overlaps if interval < function time

Which one to use?

  • Use setTimeout() when you need a one-time delay.

  • Use setInterval() for repeated actions or when you want to refresh data continuously.

You can explore our JavaScript Catalog to learn everything from basics to advanced concepts!

Knowledge test

Let’s attempt a short quiz to assess your understanding.

Q

What is the primary purpose of the setInterval() method?

A)

Execute a function repeatedly at specified intervals

B)

Run a function once after a specific delay

C)

Stop the timer after a certain period

D)

Both A and C

Conclusion

Both setTimeout() and setInterval() are essential for controlling time-based actions in JavaScript. setTimeout() is perfect for delayed, one-time executions, while setInterval() is ideal for recurring tasks. Whether you’re building a countdown timer, a notification system, or refreshing data in real-time, these methods give the flexibility to manage timing in the applications.


Frequently asked questions

Haven’t found what you were looking for? Contact Us


How to make a 10-minute timer in JavaScript?

To create a 10-minute timer, set the target time for 10 minutes in the future and use either setInterval() or setTimeout() to decrement and display the time. Convert the milliseconds to minutes and seconds for display purposes.

let countdownTime = 10 * 60 * 1000; // 10 minutes in milliseconds
let endTime = new Date().getTime() + countdownTime;

let timer = setInterval(function() {
  let currentTime = new Date().getTime();
  let timeLeft = endTime - currentTime;

  if (timeLeft <= 0) {
    clearInterval(timer);
    console.log("10-minute timer complete!");
  } else {
    let minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
    let seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);
    console.log(`Time left: ${minutes}m ${seconds}s`);
  }
}, 1000);

How to set a 1-minute timer in JavaScript?

To create a 1-minute countdown timer, set the target time for 1 minute (60 seconds) and use either setInterval() or setTimeout() to display the remaining seconds.

let countdownTime = 60 * 1000; // 1 minute in milliseconds
let endTime = new Date().getTime() + countdownTime;

let timer = setInterval(function() {
  let currentTime = new Date().getTime();
  let timeLeft = endTime - currentTime;

  if (timeLeft <= 0) {
    clearInterval(timer);
    console.log("1-minute timer complete!");
  } else {
    let seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);
    console.log(`Time left: ${seconds} seconds`);
  }
}, 1000);

How to calculate a timer in JavaScript?

To calculate a countdown timer, first determine the target end time and the current time. Subtract the current time from the target time to get the remaining time in milliseconds. Then, convert these milliseconds into minutes and seconds for display.


Free Resources

Copyright ©2024 Educative, Inc. All rights reserved