JavaScript 计时器暂停 [英] JavaScript Timer Pause

查看:55
本文介绍了JavaScript 计时器暂停的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码如下.您将如何设置按钮以在按下恢复时暂停计时器并恢复?下面的//标记是我放置暂停和恢复标签的地方.谢谢大家的帮助!!

The code is below. How would you set a button to pause the timer and resume when pressing resume? The // marks below are where I'm placing my pause and resume tags. Thank you for all of your help!!

<head>
<script type="text/javascript">

var d1 = new Date();
d1.setHours(1,0,0);

function f(){
var h= d1.getHours();
var m= d1.getMinutes();
var s=d1.getSeconds();
m= (m<10)?"0"+m: m;
s= (s<10)? "0"+s : s;

var el= document.getElementById("inputid");
el.value= h+":"+m+":"+s;
d1.setSeconds(d1.getSeconds()-1);
if( h==0 && m==0 && s==0 ) clearTimeout(t)
var t= setTimeout("f()",1000);
}

</script>
</head>
<body>
<form><input type="text" id="inputid"></form>
<script type="text/javascript">f()</script>

//pause and resume buttons would go here.
</body>

推荐答案

您可以使用 clearTimeout() 将超时从 setTimeout 传递给它,或者在您的case t.

You can stop a timeout with clearTimeout() passing it the return from setTimeout or, in your case t.

实例:http://jsfiddle.net/tJWmH/

另一个指针:不要将字符串传递给setTimeout,而是传递一个函数引用,因此:

Another pointer: dont pass a string to setTimeout, instead pass a function reference, so:

var t = setTimeout(f,1000)

代替

var t = setTimeout("f()",1000);

如果您想知道为什么,请搜索 "eval is evil".

if you're wondering why, search for "eval is evil".

这篇关于JavaScript 计时器暂停的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆