How can I create a simple JavaScript countdown timer?
I want to display a message on my site that says, “Registration closes in 05:00 minutes!” and have a countdown from “05:00” to “00:00.” Once it reaches “00:00,” I would like the timer to reset back to “05:00.” I’ve seen many examples that use Date objects and other complex methods, but I’m looking for the simplest approach possible to implement a JavaScript countdown timer.
Hi,
You can use setInterval
to update the timer every second.
let timeLeft = 300; // 5 minutes in seconds
function startCountdown() {
const timerElement = document.getElementById("timer");
const interval = setInterval(() => {
if (timeLeft <= 0) {
clearInterval(interval);
timeLeft = 300; // Reset to 5 minutes
}
// Calculate minutes and seconds
const minutes = Math.floor(timeLeft / 60);
const seconds = timeLeft % 60;
// Format time
timerElement.textContent = `Registration closes in ${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')} minutes!`;
timeLeft--;
}, 1000);
}
// Start the countdown
startCountdown();
You can use a recursive function to create the countdown effect.
let timeLeft = 300; // 5 minutes in seconds
function updateTimer() {
const timerElement = document.getElementById("timer");
if (timeLeft < 0) {
timeLeft = 300; // Reset to 5 minutes
}
const minutes = Math.floor(timeLeft / 60);
const seconds = timeLeft % 60;
timerElement.textContent = `Registration closes in ${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')} minutes!`;
timeLeft--;
setTimeout(updateTimer, 1000); // Call updateTimer again after 1 second
}
// Start the countdown
updateTimer();