Countdown Timer
Calculate remaining time by subtracting Date.now() from a future timestamp, then extract days, hours, minutes, and seconds.
Calculate remaining time by subtracting Date.now() from a future timestamp, then extract days, hours, minutes, and seconds.
function getCountdown(targetDate) {
const diff = new Date(targetDate) - Date.now();
if (diff <= 0) return { expired: true };
return {
days: Math.floor(diff / 86400000),
hours: Math.floor((diff % 86400000) / 3600000),
minutes: Math.floor((diff % 3600000) / 60000),
seconds: Math.floor((diff % 60000) / 1000),
};
}
setInterval(() => {
const { days, hours, minutes, seconds } = getCountdown("2025-01-01");
display.textContent = `${days}d ${hours}h ${minutes}m ${seconds}s`;
}, 1000);
Update countdown timers every second with setInterval — clear the interval when the timer expires.
More in JavaScript