如何在浏览器刷新时保存计数计时器?

时间:2020-04-01 15:09:54

标签: javascript

我是堆栈溢出和JavaScript的新手。我的首要任务是创建一个递增计时器。我的代码有效,但是如果刷新浏览器,我将失去计时器。我一直在阅读使用本地存储来保存位置的信息,但是我不确定如何将其添加到当前代码中。有人愿意为此提供帮助吗?这就是我当前的javascript在html文件中的外观。

     window.onload = () => {
        let day = 0;
        let hour = 0;
        let minute = 0;
        let seconds = 0;
        let totalSeconds = 0;

        let intervalId = null; 

        function startTimer() {
            ++totalSeconds;
            day = Math.floor(totalSeconds/86400);
            hour = Math.floor(totalSeconds /3600);
            minute = Math.floor((totalSeconds - hour*3600)/60);
            seconds = totalSeconds - (hour*3600 + minute*60);

            document.getElementById("day").innerHTML = day;
            document.getElementById("hour").innerHTML = hour;
            document.getElementById("minute").innerHTML = minute;
            document.getElementById("seconds").innerHTML = seconds;
        } 

        document.getElementById('start-btn').addEventListener('click', () => {
            intervalId = setInterval(startTimer, 1000);
        })

        document.getElementById('stop-btn').addEventListener('click', () => {
            if (intervalId)
                clearInterval(intervalId);
        });


        document.getElementById('reset-btn').addEventListener('click', () => {
            totalSeconds = 0;
            document.getElementById("day").innerHTML = '0';
            document.getElementById("hour").innerHTML = '0';
            document.getElementById("minute").innerHTML = '0';
            document.getElementById("seconds").innerHTML = '0';
        }); 
    }

2 个答案:

答案 0 :(得分:1)

首先,应该存储计时器启动的时间,然后计算经过的秒数,而不是存储经过的秒数。

在这里,如果本地存储中存在"start-timestamp"的值,则将startTimestamp设置为该值并激活计时器。

计时器启动时,startTimestamp设置为当前时间并存储在本地存储中,停止计时后,"start-timestamp"从本地存储中删除。

let day = 0;
let hour = 0;
let minute = 0;
let seconds = 0;
let startTimestamp = 0;

let intervalId = null; 

function updateTimer() {
    let totalSeconds = (Date.now() - startTimestamp) / 1000;
    day = Math.floor(totalSeconds/86400);
    hour = Math.floor(totalSeconds /3600);
    minute = Math.floor((totalSeconds - hour*3600)/60);
    seconds = totalSeconds - (hour*3600 + minute*60);

    document.getElementById("day").innerHTML = day;
    document.getElementById("hour").innerHTML = hour;
    document.getElementById("minute").innerHTML = minute;
    document.getElementById("seconds").innerHTML = seconds;
}

{
    const _startTimestamp = localStorage.getItem("start-timestamp");
    if (_startTimestamp) {
        startTimestamp = Number(_startTimestamp);
        intervalId = setInterval(updateTimer, 1000);
    }
}

document.getElementById('start-btn').addEventListener('click', () => {
  if (!intervalId) {
      startTimestamp = Date.now();
      localStorage.setItem("start-timestamp", startTimestamp);
      intervalId = setInterval(updateTimer, 1000);
  }
})

document.getElementById('stop-btn').addEventListener('click', () => {
    if (intervalId) {
        clearInterval(intervalId);
        localStorage.removeItem("start-timestamp");
    }
});


document.getElementById('reset-btn').addEventListener('click', () => {
    totalSeconds = 0;
    document.getElementById("day").innerHTML = '0';
    document.getElementById("hour").innerHTML = '0';
    document.getElementById("minute").innerHTML = '0';
    document.getElementById("seconds").innerHTML = '0';
});

答案 1 :(得分:0)

对于sessionStorage,请尝试以下操作检查是否已经设置了totalSeconds以及有效的数字..将totalSeconds设置为sessionStorage中存储的内容,否则设置为0:

  let tmpSession = parseInt(sessionStorage["totalSeconds"] ?? 0);
  let totalSeconds = (isFinite(tmpSession))? tmpSession : 0;

然后在增加总秒数后在startTimer()中将值写入sessionStorage,如下所示:

    sessionStorage.setItem("totalSeconds",totalSeconds);