代码如下。你会如何设置一个按钮来暂停计时器并在按下恢复时恢复?下面的//标记是我放置暂停和恢复标记的位置。感谢您的所有帮助!!
<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>
最佳答案
另一种方法是:当按下按钮时,设置一个变量,如paused
。在您的 f
函数中,如果 paused 为真,则立即返回。
setInterval(function(){
if (paused) return;
// update the dom
}, 1000);
输入
<input type="button" value="Pause" onClick="window.paused=true" />
关于JavaScript 定时器暂停,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11563382/