如何在页面刷新后防止秒表计时器重置

时间:2017-02-28 04:53:55

标签: javascript html

我有一个以page onload开头的javascript秒表。我试图让页面刷新后计数器不能重置为零。我相信我可以使用sessionStorage或localStorage。我只是不确定如何使用我已有的代码实现它。任何建议将不胜感激。

       <!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>



    <script type="text/javascript">
var timeBegan = null
    , timeStopped = null
    , stoppedDuration = 0
    , started = null;

function start() {
    if (timeBegan === null) {
        timeBegan = new Date();
    }

    if (timeStopped !== null) {
        stoppedDuration += (new Date() - timeStopped);
    }
    console.log(stoppedDuration);

    started = setInterval(clockRunning, 10);    
}

function stop() {
    timeStopped = new Date();
    clearInterval(started);
}
        function reset() {
    clearInterval(started);
    stoppedDuration = 0;
    timeBegan = null;
    timeStopped = null;
    document.getElementById("display-area").innerHTML = "00:00:00.000";
}

function clockRunning(){
    var currentTime = new Date()
        , timeElapsed = new Date(currentTime - timeBegan - stoppedDuration)
        , hour = timeElapsed.getUTCHours()
        , min = timeElapsed.getUTCMinutes()
        , sec = timeElapsed.getUTCSeconds()
        , ms = timeElapsed.getUTCMilliseconds();

    document.getElementById("display-area").innerHTML = 
        (hour > 9 ? hour : "0" + hour) + ":" + 
        (min > 9 ? min : "0" + min) + ":" + 
        (sec > 9 ? sec : "0" + sec) + "." + 
        (ms > 99 ? ms : ms > 9 ? "0" + ms : "00" + ms);
};
    </script>



</head>



<body onload="start();">
<div>
            <textarea id="display-area" style="font-size: 18px; color:chartreuse; height:22px; background-color: black; padding-left:16px; padding-right: 12px;  width:133px; border: groove; border-width: 4px; border-color: goldenrod; border-radius: 3px; resize:none; overflow:hidden">00:00:00.000</textarea>
        </div><input type="button" form="time" onclick="stop();" value="stop"></p>



</body>
</html>

1 个答案:

答案 0 :(得分:0)

看看this fiddle。它只是你想要的,在localStorage中存储开始时间并在每次加载时检索它。

function start() {
  startTime = parseInt(localStorage.getItem('startTime') || Date.now());
  localStorage.setItem('startTime', startTime);
  timer = setInterval(clockTick, 100);
}