I recently developed a countdown timer using JavaScript and included an event listener for a stop button to pause the timer
When I stopped the timer, every second was being logged individually but I wanted to only retrieve the final time value. For example, if the start time was 59:00 minutes and the stop time was 50:15 minutes, I only wanted to display the stop time of 50:15 minutes.
Please see the code snippet below:
function getTimeRemaining(endtime) { const total = Date.parse(endtime) - Date.parse(new Date()); const seconds = Math.floor((total / 1000) % 60); const minutes = Math.floor((total / 1000 / 60) % 60); const hours = Math.floor((total / (1000 * 60 * 60)) % 24); const days = Math.floor(total / (1000 * 60 * 60 * 24)); return { total, days, hours, minutes, seconds }; } 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'); /* buttons */ const startbutton = document.getElementById('Startbtn') const stopbtton = document.getElementById('Stopbtn'); 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); } else { stopbtton.addEventListener('click', (e) => { clearInterval(timeinterval); var StopTime = t.minutes + ":" + t.seconds; console.log(StopTime); // returned as a single item }) } } // updateClock(); const timeinterval = setInterval(updateClock, 1000); } const deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000); initializeClock('clockdiv', deadline);
How can I ensure that only the last stop time value is displayed instead of each individual second?
Your help is greatly appreciated!