JavaScript Program to Create Countdown Timer (4 Ways)
A countdown timer is widely used in web applications to track time remaining for events, product launches, online tests, or reminders. JavaScript provides multiple ways to create countdown timers that can be displayed on web pages and updated dynamically.
For example:
-
Countdown to an event happening in 10 minutes.
-
Showing the remaining time for an offer expiration.
This guide explains various methods to create a countdown timer in JavaScript, including dynamic updates and custom styling.
Countdown Timer in JavaScript Using setInterval()
The setInterval() function can be used to run code at specified time intervals, making it ideal for countdown timers.
Code
function startCountdown(seconds) {
let remainingTime = seconds;
const timer = setInterval(() => {
const minutes = Math.floor(remainingTime / 60);
const sec = remainingTime % 60;
console.log(`${minutes} minutes and ${sec} seconds remaining`);
remainingTime--;
if (remainingTime < 0) {
clearInterval(timer);
console.log('Countdown completed!');
}
}, 1000);
}
// Start a countdown for 5 minutes
startCountdown(300);
Output
4 minutes and 59 seconds remaining
4 minutes and 58 seconds remaining
...
Countdown completed!
Explanation
-
The setInterval() function decreases the time every second.
-
When the countdown reaches zero, the interval is cleared using clearInterval().
Displaying Countdown on Web Page in JavaScript
HTML:
<p id="countdown"></p>
Code
function displayCountdown(duration) {
let remainingTime = duration;
const countdownElement = document.getElementById('countdown');
const timer = setInterval(() => {
const minutes = Math.floor(remainingTime / 60);
const seconds = remainingTime % 60;
countdownElement.innerText = `${minutes} min ${seconds} sec remaining`;
remainingTime--;
if (remainingTime < 0) {
clearInterval(timer);
countdownElement.innerText = 'Time is up!';
}
}, 1000);
}
displayCountdown(300);
Output
4 min 59 sec remaining
4 min 58 sec remaining
...
Time is up!
You can dynamically update an HTML element to display the countdown.
Explanation
-
The countdown dynamically updates the page every second.
-
When the countdown ends, the message "Time is up!" is displayed.
Countdown Timer with Start, Pause, and Reset in JavaScript
HTML:
<p id="countdown-display">00:00</p>
<button onclick="startTimer()">Start</button>
<button onclick="pauseTimer()">Pause</button>
<button onclick="resetTimer()">Reset</button>
Code
let countdown;
let timeLeft = 180;
function updateDisplay() {
document.getElementById('countdown-display').innerText =
`${Math.floor(timeLeft / 60)}:${timeLeft % 60}`;
}
function startTimer() {
countdown = setInterval(() => {
if (timeLeft <= 0) {
clearInterval(countdown);
document.getElementById('countdown-display').innerText = 'Time Up!';
} else {
timeLeft--;
updateDisplay();
}
}, 1000);
}
function pauseTimer() {
clearInterval(countdown);
}
function resetTimer() {
clearInterval(countdown);
timeLeft = 180;
updateDisplay();
}
updateDisplay();
Output
3:00
2:59
...
Time Up!
Adding control buttons to start, pause, and reset the countdown.
Explanation
-
Users can start, pause, and reset the countdown.
-
The timer updates the display every second.
Countdown Time in JavaScript to a Specific Date and Time
A countdown can be set for a specific future date and time.
Code
function countdownToDate(targetDate) {
const timer = setInterval(() => {
const now = new Date().getTime();
const timeDifference = targetDate - now;
if (timeDifference <= 0) {
clearInterval(timer);
console.log('The event has started!');
} else {
const days = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
const hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((timeDifference % (1000 * 60)) / 1000);
console.log(`${days}d ${hours}h ${minutes}m ${seconds}s remaining`);
}
}, 1000);
}
const eventDate = new Date('2024-12-31T00:00:00').getTime();
countdownToDate(eventDate);
Output
365d 5h 23m 12s remaining
365d 5h 23m 11s remaining
...
The event has started!
Explanation
-
The script calculates the time difference between the current time and the target date.
-
When the countdown reaches zero, the message "The event has started!" appears.
Concepts Used in above Countdown Timers
Time Calculation
-
Using Math.floor() to calculate minutes and seconds.
Dynamic Updates
-
setInterval() to update countdown values in real-time.
DOM Manipulation
-
Using document.getElementById() to display countdown on a webpage.
Event Handling
-
Adding event listeners to start, pause, and reset timers.