Skip to content Skip to sidebar Skip to footer

How Do I Store My Countdown Timer In A Cookie So That It Will Continue Counting Down Even When Leaving Or Reloading The Page?

My webpage should display a countdown timer which right now is set to 1hour. I want to store the countdown in a cookie so that even when I leave the page, the timer will continue c

Solution 1:

Instead of cookies, I made an example that uses localStorage, but I think it still gets the point across. StackOverflow doesn't allow snippets to use localStorage so I deployed it here:

Example Site

https://lab-btmhicjaje.now.sh

Source Code

https://lab-btmhicjaje.now.sh/_src

HTML

<spanclass="mdl-chip"><spanclass="mdl-chip__text"id="timer"></span></span><br><buttonclass="mdl-button mdl-js-button mdl-button--colored"onclick="startTimer()">Start</button><buttonclass="mdl-button mdl-js-button mdl-button--colored"onclick="stopTimer()">Lap</button><buttonclass="mdl-button mdl-js-button mdl-button--colored"onclick="resetTimer()">Reset</button>

JavaScript

document.addEventListener('DOMContentLoaded', () => {
if (localStorage.getItem('timerRunning') === 'true')
    startTimer();
elsedisplayTime(parseInt(localStorage.getItem('timestamp')));
});
let timer;
let startTimestamp = parseInt(localStorage.getItem('timestamp'));
functiondisplayTime(timestamp) {
    if (timestamp)
        display(Date.now() - timestamp);
    elsedisplay(0);
}
functionstartTimer() {
    let timestamp = parseInt(localStorage.getItem('timestamp')) || Date.now();
    localStorage.setItem('timestamp', timestamp.toString());
    localStorage.setItem('timerRunning', 'true');
    clearInterval(timer);
    timer = setInterval(() =>displayTime(timestamp), 100);
}
functionstopTimer() {
    localStorage.setItem('timerRunning', 'false');
    clearInterval(timer);
}
functionresetTimer() {
    localStorage.removeItem('timestamp');
    display(0);
}
functiondisplay(milliseconds) {
    let el = document.getElementById('timer');
    if (el)
        el.innerHTML = msToTime(milliseconds);
}
//https://coderwall.com/p/wkdefg/converting-milliseconds-to-hh-mm-ss-mmmfunctionmsToTime(duration) {
    var milliseconds = parseInt((duration % 1000) / 100), seconds = parseInt((duration / 1000) % 60), minutes = parseInt((duration / (1000 * 60)) % 60), hours = parseInt((duration / (1000 * 60 * 60)) % 24);
    hours = (hours < 10) ? "0" + hours : hours;
    minutes = (minutes < 10) ? "0" + minutes : minutes;
    seconds = (seconds < 10) ? "0" + seconds : seconds;
    return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}

Post a Comment for "How Do I Store My Countdown Timer In A Cookie So That It Will Continue Counting Down Even When Leaving Or Reloading The Page?"