首页 > 解决方案 > 刷新时的持久性倒计时

问题描述

我有一个问题要解决,我不是 javascript 的大师,基本上当加载我的元素 id 时,它会在我的代码中从 2 小时分秒开始倒计时,但我有链接,点击刷新页面和正在刷新我的计数器我发现完整的计数器是链接: JavaScript 倒计时,添加小时和分钟

var count = 7200;
var counter = setInterval(timer, 1000); //1000 will  run it every 1 second

function timer() {
    count = count - 1;
    if (count == -1) {
        clearInterval(counter);
        return;
    }

    var seconds = count % 60;
    var minutes = Math.floor(count / 60);
    var hours = Math.floor(minutes / 60);
    minutes %= 60;
    hours %= 60;

    document.getElementById("timer").innerHTML = hours + " ora " + minutes + " minute" + seconds + " secunde ramase ";
}

我只是想让这个计数器在刷新时不重置。

标签: javascriptphpjqueryhtml

解决方案


使用localStorage

var count = parseInt(localStorage.getItem("count")) || 7200;

function timer() {
    //...
    document.getElementById("timer").innerHTML = hours + " ora " + minutes + " minute" + seconds + " secunde ramase ";
    localStorage.setItem("count", count);
}

要重定向您的页面并localStorage在计时器命中时清除0,请将此代码添加到您的函数中:

function timer() {
    count = count - 1;
    if (count == 0) {
        localStorage.removeItem("count");
        window.location.href = "home.html";
    }
    //...
}

推荐阅读