刷新页面时如何使倒数计时器不从头开始

时间:2018-09-02 00:09:15

标签: javascript html countdown countdowntimer

我从this repository获得了倒计时代码,并且进行了一些更改,并且我希望在刷新页面时不要从一开始就倒计时,我的Js代码是:

var timeleft =5400;

var startTime = 0;
var currentTime = 0;

function convertSeconds(s) {
    var decimal = (s/3600) - Math.floor((s/3600))
    var h = floor(s/3600);
    var min = floor(decimal * 60) ;
    var sec = s % 60;
    return nf(h, 2) + ':' + nf(min, 2) + ':' + nf(sec, 2);
}

function setup() {
    noCanvas();
    startTime = millis();

    var timer = select('#timer');
    timer.html(convertSeconds(timeleft - currentTime));

    var interval = setInterval(timeIt, 1000);

    function timeIt() {
        currentTime = floor((millis() - startTime) / 1000);
        timer.html(convertSeconds(timeleft - currentTime));
        if (currentTime == timeleft) {
            clearInterval(interval);
        }
    }
}

我的HTML代码:

<html>
<head>
    <meta charset="UTF-8">
    <script language="javascript" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>
    <script language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/addons/p5.dom.js"></script>
    <script language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/addons/p5.sound.js"></script>
    <script language="javascript" type="text/javascript" src="chrono.js"></script>
</head>
<body>
    <p id="timer"></p>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您可以将当前计数器值存储到本地存储(如果使用html 5,则为cookie或其他选项),并在加载页面时读取其值并基于该值启动计时器。

Andrew建议在每次开始存储间隔时都存储一个时间戳。然后在加载时,您可以通过将当前时间戳记减去存储的时间戳记来获得增量