24-Hour Countdown with Progress Saving Using Vanilla JavaScript

on in JavaScript DOM, JavaScript Time & Date
Last modified on

Here’s an interesting JavaScript snippet allowing you to set a 24-hour countdown and save its progress, so that on the next page reload or the next visit, it will start where it left off.

See a live demo here.

HTML

<div id="countdown"></div>

JavaScript

function countdown(elementName, minutes, seconds) {
    let element, endTime, hours, mins, msLeft, time;

    function twoDigits(n) {
        return (n <= 9 ? '0' + n : n);
    }

    function updateTimer() {
        msLeft = endTime - (+new Date);

        if (msLeft < 1000) {
            element.innerHTML = '0:00';
        } else {
            time = new Date(msLeft);
            hours = time.getUTCHours();
            mins = time.getUTCMinutes();
            element.innerHTML = (hours ? hours + ':' + twoDigits(mins) : mins) + ':' + twoDigits(time.getUTCSeconds());

            // Save current time locally
            localStorage.setItem('lastHValue', hours);
            localStorage.setItem('lastMValue', mins);
            localStorage.setItem('lastSValue', time.getUTCSeconds());

            setTimeout(updateTimer, time.getUTCMilliseconds() + 500);
        }
    }

    element = document.getElementById(elementName);
    endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;

    updateTimer();
}

if (localStorage.getItem('lastHValue')) {
    let lastHValue = parseInt(localStorage.getItem('lastHValue')),
        lastMValue = parseInt(localStorage.getItem('lastMValue')),
        lastSValue = parseInt(localStorage.getItem('lastSValue'));

    let totalMValue = parseInt((lastHValue * 60) + lastMValue);

    countdown('countdown', totalMValue, lastSValue);
} else {
    countdown('countdown', 1439, 59);
}

Note the last line, the function call:

countdown('countdown', 1439, 59);

That value is 1440 minutes, which is 24 hours. In order to have an accurate duration, I eliminated one second, and started from 1439 minutes and 59 seconds.

Related posts