Hello all. I have an events website and a countdown timer. The countdown works, but I’m seeing some strange behaviour when the time elapses.
Here’s an example of the timer working. This event is tomorrow (20th June) - which is approximately 8 hours away (until midnight):
If the event is today (19th June) - from looking at the code I’d expect the counters to display 0, and my custom message to be shown - however, the numbers are appearing as negatives, and my custom message is still hidden:
It’s probably really obvious, but I didn’t write this snippet.
Any help would be greatly appreciated as always.
(function () {
const second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24;
// Set the target date and time for the countdown (format: "MM/DD/YYYY HH:mm:ss")
const targetDateString = "06/20/2024 00:00:00";
const targetDate = new Date(targetDateString).getTime();
const updateCountdown = () => {
const now = new Date().getTime(), // Get the current date and time
distance = targetDate - now; // Calculate the time remaining until the target date
// Update the HTML elements with the remaining time
document.getElementById('days').innerText = Math.floor(distance / day);
document.getElementById('hours').innerText = Math.floor((distance % day) / hour);
document.getElementById('minutes').innerText = Math.floor((distance % hour) / minute);
document.getElementById('seconds').innerText = Math.floor((distance % minute) / second);
// Check if the target date has already passed
if (distance < 0) {
clearInterval(interval); // Stop the countdown timer
document.getElementById('days').innerText = '0';
document.getElementById('hours').innerText = '0';
document.getElementById('minutes').innerText = '0';
document.getElementById('seconds').innerText = '0';
// You can display an element at the end of the countdown with this ID
document.getElementById('todaymessage').style.display = 'block';
}
};
// Initial call to update countdown
updateCountdown();
// Update the countdown every second
const interval = setInterval(updateCountdown, 1000);
})();