在下面的脚本中,我尝试制作某种秒表:
<html>
<head>
<script>
var t; var time; var timetoRun=180000;// 3 min
function Timer()
{
stoper = (this.startTime+ this.timetoRun)-new Date().getTime();
x = parseInt(stoper / 1000);
s = x % 60;
x = parseInt(x/60);
m = x % 60;
if (s<10) s='0'+ s;document.getElementById('txt').innerHTML=m+':'+s;
this.t=setTimeout(function(){Timer()},500);
}
function myStopFunction(){clearTimeout(t);}
function init(){this.startTime = new Date().getTime();}
</script>
</head>
<body onload="init()">
<div id="txt"></div>
<button onclick="myStopFunction()">Stop time</button>
<button onclick="Timer()">Start time</button>
</body>
</html>
问题是:当我在2:28
停止时间并在5秒后再次开始时。值立即跳转到 2:23
。我想要实现的是:将时间停止在(例如)2:31
并从 2:31
再次运行。
提前致谢。
最佳答案
您可以简化很多代码,以避免使用 Date
对象。
此外,您还忘记了一些 var
关键字和一个在时间用完时停止计时器的条件。我还插入了一个 resetTimer
方法,因此如果您需要重新启动计时器两次或更多次,它将再次设置为 180
秒
代码笔示例:http://codepen.io/anon/pen/Duier
代码
var
// seconds
timetoRun,
// cache a reference to the DOM element in which you update the timer
timeElement,
// your interval
intv;
function Timer() {
var ss = timetoRun % 60;
var mm = (timetoRun / 60) | 0; // Math.floor
if (ss < 10) ss = '0' + ss;
timeElement.innerHTML = [mm,ss].join(":");
if (timetoRun-- > 0) {
intv = setTimeout(Timer, 1000);
}
else {
myStopFunction();
resetTimer();
}
};
function myStopFunction() { clearInterval(intv); };
function resetTimer() {
timetoRun = 180 //second;
};
function init() {
resetTimer();
timeElement = document.getElementById('txt');
};
关于javascript - javascript 中的秒表使用新的 Date 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21782369/