function initializeClock(id, endtime) {
const clock = document.getElementById(id);
const daysSpan = clock.querySelector('.days');
const hoursSpan = clock.querySelector('.hours');
const minutesSpan = clock.querySelector('.minutes');
const secondsSpan = clock.querySelector('.seconds');
function updateClock() {
const t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
const timeinterval = setInterval(updateClock, 1000);
}
initializeClock()
takes two parameters: id
(the ID of the HTML element where the timer will be displayed) and endtime
(the deadline).updateClock()
retrieves the remaining time using the getTimeRemaining()
function and updates the corresponding spans (days
, hours
, minutes
, seconds
).setInterval()
ensures that the updateClock()
function runs every second (1000 milliseconds).- If the total remaining time becomes zero or negative, the interval is cleared, stopping the countdown.