JAVASCRIPT PROJECT 08

Build a JavaScript Countdown Timer

In this project, you will learn how to create a countdown timer using JavaScript Date objects, mathematical calculations, setInterval() and DOM manipulation.

01

Project Introduction

A countdown timer counts down from a selected amount of time until it reaches zero.

What You Will Learn

  • JavaScript Date objects
  • Time calculations
  • setInterval()
  • DOM manipulation
  • Functions
  • Conditional statements
  • Input handling
Target Select when the countdown should finish.
Calculate Find the remaining time.
Update Display the remaining time.
02

Create the HTML Structure

First, create an input for the target date and a display for the remaining time.

<input
    type="datetime-local"
    id="targetDate"
>

<button onclick="startCountdown()">
    Start Countdown
</button>

<div id="countdown">
    00:00:00:00
</div>
The datetime-local input allows the user to select both a date and a time.
03

Get the Target Date

JavaScript can read the value entered into the datetime input.

const input =
    document.getElementById("targetDate");

const target =
    new Date(input.value);

The Date object converts the selected date and time into a JavaScript date value.

04

Understand the JavaScript Date Object

The Date object allows JavaScript to work with dates and times.

const now = new Date();

console.log(now);

Get Current Time in Milliseconds

const currentTime =
    new Date().getTime();
JavaScript represents time internally using milliseconds.
05

Calculate the Time Difference

Subtract the current time from the target time.

const now =
    new Date().getTime();

const target =
    new Date(input.value).getTime();

const difference =
    target - now;

The result is the number of milliseconds remaining.

06

Convert Milliseconds into Time

We can convert milliseconds into days, hours, minutes and seconds.

Days

const days =
    Math.floor(
        difference /
        (1000 * 60 * 60 * 24)
    );

Hours

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

Minutes and Seconds

const minutes =
    Math.floor(
        (difference %
        (1000 * 60 * 60))
        /
        (1000 * 60)
    );

const seconds =
    Math.floor(
        (difference %
        (1000 * 60))
        /
        1000
    );
07

Update the Countdown Display

Display the calculated values inside the HTML element.

countdown.textContent =
    days + " Days " +
    hours + " Hours " +
    minutes + " Minutes " +
    seconds + " Seconds";

Better Format

countdown.textContent =
    String(days).padStart(2, "0")
    + ":" +
    String(hours).padStart(2, "0")
    + ":" +
    String(minutes).padStart(2, "0")
    + ":" +
    String(seconds).padStart(2, "0");
08

Use setInterval()

The countdown needs to update every second. setInterval() is useful for this.

const timer =
    setInterval(function(){

        updateCountdown();

    }, 1000);
1000 milliseconds equals one second, so the countdown updates once every second.
09

Stop When the Countdown Finishes

When the remaining time reaches zero, clear the interval.

if(difference <= 0){

    clearInterval(timer);

    countdown.textContent =
        "00:00:00:00";

}

This prevents the countdown from continuing into negative values.

10

Create a Reset Function

Reset should stop the timer and restore the default display.

function resetCountdown(){

    clearInterval(timer);

    countdown.textContent =
        "00:00:00:00";

}
clearInterval() is important because it stops the previously created countdown interval.

Complete Project Flow

INPUT Target Date
DATE Current Time
CALCULATE Difference
UPDATE Every Second
FINISH Zero
12

Complete Countdown Timer

You have now learned how to calculate remaining time, update a countdown every second and stop it when it reaches zero.

Tutorial Completed! ⏳

Now open the complete working Countdown Timer and test everything you have learned.

Run Complete Project Learn JavaScript Date