I created a countdown timer in JavaScript but I can’t figure out how to stop it when I need to. The timer keeps running and I want to be able to halt it at certain points. I tried looking online but most examples don’t show the stopping part clearly.
Here’s what I have so far:
const timerID = setInterval(() => {
updateTimer();
}, 1000);
const updateTimer = () => {
const targetDate = new Date('December 25, 2024 00:00:00').getTime();
const currentTime = new Date().getTime();
const difference = targetDate - currentTime;
const msInSecond = 1000;
const msInMinute = msInSecond * 60;
const msInHour = msInMinute * 60;
const msInDay = msInHour * 24;
const remainingDays = Math.floor(difference / msInDay);
const remainingHours = Math.floor((difference % msInDay) / msInHour);
const remainingMinutes = Math.floor((difference % msInHour) / msInMinute);
const remainingSeconds = Math.floor((difference % msInMinute) / msInSecond);
document.getElementById('day-counter').textContent = remainingDays;
document.getElementById('hour-counter').textContent = remainingHours;
document.getElementById('minute-counter').textContent = remainingMinutes;
document.getElementById('second-counter').textContent = remainingSeconds;
};
I’m still learning JavaScript so any help would be great. Thanks!