How do I store my countdown timer in a cookie so that it will continue counting down even when leaving or reloading the page?

你。 提交于 2020-01-25 08:36:05

问题


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 counting down. I am beginner in using cookies in javascript so I really need some help on what I am doing wrong here.

Here's my html code

<b id="timer">00:00:00</b><br>
<button id="start">Start</button>
<button id="stop" hidden>Stop</button>

Javascript

var counter=0;
var timeleft=3600;

//function that returns countdown format 00:00:00
function convertSeconds(s){
    var hr=Math.floor(s/3600);
    var min=Math.floor(s/60%60);
    var sec=s%60;
    return ("0" + hr).slice(-2) + ':' + ("0" + min).slice(-2) + ':' + ("0" + sec).slice(-2);
}

//cookie expire time variable set to 1hr
var now = new Date();
var time = now.getTime();
time += 3600 * 1000;
now.setTime(time);

var cd = document.getElementById("timer");

if(document.cookie.length != 0){
    var carray = document.cookie.split("=");
    cd.innerHTML=carray[1]; //should display initial countdown duration before btnstart is clicked
    function timeIt(){ //function that displays the dynamic countdown timer
        counter++;
        cd.innerHTML=carray[1];
    }
}

var btnstart = document.getElementById("start");
var btnstop = document.getElementById("stop");

//starts countdown when btnstart clicked
btnstart.onclick = function()
{
    //storing the countdown format to a cookie and setting expire time to 1hour
    document.cookie = "cdanim=" + convertSeconds(timeleft-counter); + ";expires=" + now.toUTCString();
    setInterval(timeIt, 1000); //starts the countdown
    btnstart.hidden=true;
    btnstop.hidden=false;
}

Right now it displays some random texts which I have no idea where it came from, instead of displaying the countdown itself. carray[1] should be returning 1:00:00 but its not. Please help.


回答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

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

JavaScript

document.addEventListener('DOMContentLoaded', () => {
if (localStorage.getItem('timerRunning') === 'true')
    startTimer();
else
    displayTime(parseInt(localStorage.getItem('timestamp')));
});
let timer;
let startTimestamp = parseInt(localStorage.getItem('timestamp'));
function displayTime(timestamp) {
    if (timestamp)
        display(Date.now() - timestamp);
    else
        display(0);
}
function startTimer() {
    let timestamp = parseInt(localStorage.getItem('timestamp')) || Date.now();
    localStorage.setItem('timestamp', timestamp.toString());
    localStorage.setItem('timerRunning', 'true');
    clearInterval(timer);
    timer = setInterval(() => displayTime(timestamp), 100);
}
function stopTimer() {
    localStorage.setItem('timerRunning', 'false');
    clearInterval(timer);
}
function resetTimer() {
    localStorage.removeItem('timestamp');
    display(0);
}
function display(milliseconds) {
    let el = document.getElementById('timer');
    if (el)
        el.innerHTML = msToTime(milliseconds);
}
//https://coderwall.com/p/wkdefg/converting-milliseconds-to-hh-mm-ss-mmm
function msToTime(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;
}


来源:https://stackoverflow.com/questions/46312941/how-do-i-store-my-countdown-timer-in-a-cookie-so-that-it-will-continue-counting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!