2017-02-28 183 views
1

我有一個javascript page stop,以page onload開頭。我試圖在刷新頁面後讓計數器重置爲零。我相信我可以使用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> 
+0

使用本地緩存。 –

+0

每當秒錶開始,停止或「滴答」時,將其當前值存儲在localStorage中,並存儲停止/運行狀態標誌。然後在頁面加載時,您可以檢查存儲的詳細信息並根據需要設置/啓動秒錶。 – nnnnnn

回答

0

看看this fiddle。它只是你想要的,將開始時間存儲在localStorage中,並在每次加載時檢索它。

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

非常棒!我現在看到並理解它。感謝您傳播知識! –

+0

@ J.Parker,你可以設置這個問題解決? – t3mplar

相關問題