我在我的網頁上使用了一個計時器。計時器是使用JavaScript代碼構建的。函數startTimer()在「body onload」上調用。所以每次頁面重新加載時,函數startTimer()都會被調用並且定時器會被重置。我們如何避免它?換句話說,只有在第一次加載主體時,我們纔可以調用該函數。 以下是函數startTimer()的代碼。使用javascript構建的計時器在刷新頁面時會重置?如何避免它?
<script type="text/javascript">
var running = false;
var endTime = null;
var timerID = null;
function startTimer() {
running = true;
now = new Date();
now = now.getTime();
// change last multiple for the number of minutes
endTime = now + (1000 * 60 * 140);
showCountDown();
}
function showCountDown() {
var now = new Date();
now = now.getTime();
if (endTime - now == 0) {
//stopTimer();
alert("Time is up.");
document.form1.submit();
} else {
var delta = new Date(endTime - now);
var theMin = delta.getMinutes();
var theSec = delta.getSeconds();
var theTime = theMin;
if(theMin==59){alert("Time is up.");
document.form1.submit();}
theTime += ((theSec < 10) ? ":0" : ":") + theSec;
document.form1.timerDisplay.value = theTime;
if (running) {
timerID = setTimeout("showCountDown()",1000);
}
}
}
function stopTimer() {
clearTimeout(timerID);
running = false;
document.form1.timerDisplay.value = "0:00";
}
</script>
函數上面被稱爲如下:
<body onload="startTimer();">