Javascript计时器页面刷新

时间:2019-06-12 17:47:54

标签: javascript cookies countdown

我将计时器设置为从10分钟开始倒计时。我需要它,所以当用户刷新页面时,它不会重置计时器。这是我的JavaScript。

function startTimer(duration, display) {
var start = Date.now(),
    diff,
    minutes,
    seconds;
function timer() {
    // get the number of seconds that have elapsed since 
    // startTimer() was called
    diff = duration - (((Date.now() - start) / 1000) | 0);

    // does the same job as parseInt truncates the float
    minutes = (diff / 60) | 0;
    seconds = (diff % 60) | 0;

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds; 

    if (diff <= 0) {
        // add one second so that the count down starts at the full     duration
        // example 05:00 not 04:59
        start = Date.now() + 1000;
    }
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}

window.onload = function () {
var fiveMinutes = 60 * 10,
    display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};

1 个答案:

答案 0 :(得分:2)

现在是2019年。我强烈建议您使用localStorage或sessionStorage代替cookie。

const start = localStorage.getItem('startTime') || Date.now();
// ...rest of your code...
window.onload = function() {
    localStorage.setItem('startTime', start);
    // ...rest of your code...
};

在设置localStorage.setItem的值之后,您可能希望将startTimer位放在start函数中。取决于您想要的细节。

相关问题