May 04
今天有人问我,自己写的一个计时器,能开始,却不能停止。他原来的clearTimeout中的方法没有带句柄,不过可以用下面的方法来自动获取计时器的句柄window.clearTimeout(setTimeout("0")-1); 完整的测试代码如下:
<html>
<head>
<script language="javascript" type="text/javascript" >
var mill=0; sec=0;var min=0;var hou=0;var enable=0;
function update(){
//alert('ok');
mill++;
if(mill==100){mill=0;sec+=1;}
if(sec==60){sec=0;min+=1;}
if(min==60){min=0;hou+=1;}
var v= document.getElementById('textName');
v.value=(hou+"时"+min+"分"+sec+"秒"+mill+"毫秒");
idt=window.setTimeout("update();",10);
}
function timestop(){
alert('stop');
window.clearTimeout(setTimeout("0")-1);
// window.clearTimeout("update();");
}
</script>
</head>
<body>
<form name="frm1">
<div id="txttime"> </div>
<input name="textName" type="text" id="textName" />
<script language="javascript" type="text/javascript" >
update();
</script>
<input type="button" onclick="javascript:timestop()" value="stop" />
</form>
</body>
</html>