2017-02-28 153 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

相关问题