Javascript定时器页面刷新

标签 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);
};

最佳答案

现在是 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...
};

在设置 start 的值后,您可能需要将 localStorage.setItem 位放入 startTimer 函数中。取决于您想要的详细信息。

关于Javascript定时器页面刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56567789/

相关文章:

Javascript递归函数不起作用

javascript - 未捕获的 SyntaxError : Invalid regular expression: missing/, 我缺少什么?

javascript - Node.js cookie 解析器返回编码字符

javascript - 使用 Javascript 获取 Cookie

javascript - 基本的 Javascript 倒计时

javascript - 在 on() 事件中创建动态选择器

javascript - MongoDB : how to put conditional for multiple optional value

asp.net - SameSite None 未在 Azure Web App 中设置 cookie 属性

javascript - element.html() 在 DOM 就绪时返回空

javascript - 每小时倒数计时器,但以 30 分钟标记