考试结束后如何停止计时器?
我想在考试结束时但在它达到零之前停止这个计时器。请帮助我编写脚本。谢谢。
JavaScript 代码:
var cnt = 165*60; // 165 minutes (2 hours & 45 minutes) convert to seconds
function countdown() {
if (cnt < 0) {
document.f.c.value = "- : - - : - -" ;
}
else {
hour = Math.floor(cnt / 3600);
totalmin = Math.floor(cnt / 60);
min = totalmin - (hour * 60);
sec = cnt - (totalmin * 60);
if (sec < 10) { sec = "0" + sec;}
if (min < 10) {min = "0" + min;}
if (hour < 10) {hour = "0" + hour;}
document.f.c.value = hour + ":" + min + ":" + sec;
cnt--;
_timer = setTimeout("countdown()", 1000);
}
}
var _timer = setTimeout("countdown()", 1000); // tick
I want to stop this timer when I end the exam, but before it reaches zero. Kindly help me out on scripts please. Thanks.
JavaScript code:
var cnt = 165*60; // 165 minutes (2 hours & 45 minutes) convert to seconds
function countdown() {
if (cnt < 0) {
document.f.c.value = "- : - - : - -" ;
}
else {
hour = Math.floor(cnt / 3600);
totalmin = Math.floor(cnt / 60);
min = totalmin - (hour * 60);
sec = cnt - (totalmin * 60);
if (sec < 10) { sec = "0" + sec;}
if (min < 10) {min = "0" + min;}
if (hour < 10) {hour = "0" + hour;}
document.f.c.value = hour + ":" + min + ":" + sec;
cnt--;
_timer = setTimeout("countdown()", 1000);
}
}
var _timer = setTimeout("countdown()", 1000); // tick
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我假设您的意思是您希望在倒计时达到 0 之前结束计时器。
首先,您应该使用
setInterval
来代替。它应该适用于所有主要浏览器(包括 IE)。这只是表达“我希望这种情况经常发生”的一种稍微好一点的方式。根据 MDN,它:使用方法如下:
页面中的某处有一个可以停止计时器的按钮。
虽然说实话,倒计时器让我感到害怕。我宁愿有一个倒计时。 :-)
I assume you meant that you want to end the timer before the countdown reaches 0.
First of all, you should use
setInterval
instead. It should work in all major browsers (including IE). It is just a slightly nicer way to express "I want this to happen every so often." According to the MDN, it:Here's how you would use it:
And somewhere in your page have a button that will stop the timer.
Although to be honest, having a countdown timer freaks me out. I'd rather have a count-up timer. :-)
在你的其他部分
查看
In your else part
check
我认为最好的选择是使用 setInterval 而不是 setTimeout。
setInterval 返回间隔的句柄。 clearInterval(handle) 将取消该间隔。这里有一些伪代码可以帮助您入门:
I think your best bet here is to use setInterval rather than setTimeout.
setInterval returns a handle to the interval. clearInterval(handle) will cancel that interval. Here's some pseudo to get you started:
在用户结束考试时执行的代码中,可能在单击按钮后,只需添加这样的行:
计时器将停止计时。
In the code that you execute when user ends the exam, probably after button click, just add such line:
And the timer will stop ticking.