Javascript 秒表不从零开始
我这里有一个基本的秒表,但问题是我认为它在页面加载时开始计数,而不是在单击开始按钮时开始计数。同样,当您重置并重新启动时,也会发生同样的问题。
<form>
<input type="button" value="Start count!" onclick="doTimer()" />
<input type="text" id="txt" />
<input type="button" value="Stop count!" onclick="stopCount()" />
<input type="button" value="Reset!" onclick="resetCount()" />
</form>
<script type="text/javascript">
var start = new Date().getTime();
var elapsed = '0.0';
var t;
var timer_is_on=0;
function timedCount() {
var time = new Date().getTime() - start;
elapsed = Math.floor(time / 100) / 10;
if(Math.round(elapsed) == elapsed) { elapsed += '.0'; }
document.getElementById('txt').value=elapsed;
t=setTimeout("timedCount()",50);
}
function doTimer() {
if (!timer_is_on) {
timer_is_on=1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on=0;
}
function resetCount() {
document.getElementById('txt').value='0.0';
var elapsed = '0.0';
}
</script>
我尝试定义开始按钮的开始变量 onclick,但到目前为止还没有取得太大成功。非常感谢任何帮助,谢谢。
I've got a basic stopwatch here, but the problem is I think it begins counting when the page loads as opposed to when the start button is clicked. Likewise, when you reset and start again the same problem happens.
<form>
<input type="button" value="Start count!" onclick="doTimer()" />
<input type="text" id="txt" />
<input type="button" value="Stop count!" onclick="stopCount()" />
<input type="button" value="Reset!" onclick="resetCount()" />
</form>
<script type="text/javascript">
var start = new Date().getTime();
var elapsed = '0.0';
var t;
var timer_is_on=0;
function timedCount() {
var time = new Date().getTime() - start;
elapsed = Math.floor(time / 100) / 10;
if(Math.round(elapsed) == elapsed) { elapsed += '.0'; }
document.getElementById('txt').value=elapsed;
t=setTimeout("timedCount()",50);
}
function doTimer() {
if (!timer_is_on) {
timer_is_on=1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on=0;
}
function resetCount() {
document.getElementById('txt').value='0.0';
var elapsed = '0.0';
}
</script>
I've tried defining the start variable onclick of the start button but not had much success so far. Any help is much appreciated thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须在
doTimer()
中包含另一个重置:请在此处。
You'll have to include another reset in
doTimer()
:See the running version here.
您遇到的问题是您在页面加载后立即记录
开始
,而不是在用户实际单击开始按钮时记录。要记录用户实际单击按钮时的开始,请将doTimer
函数更改为以下内容The problem you're having is your recording the
start
as soon as the page loads instead of when the user actually clicks on the start button. To record the start when the user actually clicks on the button change yourdoTimer
function to the folowing