簡體   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