Creating a Countdown Timer using JavaScript
Overview
A countdown timer is a common feature in web applications, especially in scenarios like online tests, auctions, or waiting pages. This JavaScript snippet shows how to create a simple yet effective countdown timer, which can be easily integrated and customized in various web projects.
Code
Countdown Timer Function
function startCountdown(duration, display) {
let timer = duration,
minutes,
seconds;
const interval = setInterval(() => {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
clearInterval(interval);
display.textContent = "Time's up!";
}
}, 1000);
}
Example Usage
Setting Up the Timer
window.onload = function () {
const fiveMinutes = 60 * 5,
display = document.querySelector("#time");
startCountdown(fiveMinutes, display);
};
HTML Structure
<span id="time">05:00</span>
Code Description
The startCountdown
function creates a countdown timer:
- Purpose: To count down from a specified duration (in seconds) and update a display element with the remaining time.
- Implementation: Uses
setInterval
to decrease the timer every second, formats the time into minutes and seconds, and updates the display. The interval is cleared when the timer reaches zero. - Return Value: None. The function updates the DOM directly.
This function is ideal for real-time countdown displays in quizzes, games, or any scenario requiring precise time management.