繁体   English   中英

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

[英]How to prevent stopwatch timer reset after page refresh

我有一个以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>

看看这个小提琴 它只是你想要的,在localStorage中存储开始时间并在每次加载时检索它。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM