<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>计时器</title> <script type="text/javascript"> var num=0; function startCount() { document.getElementById('count').value=num; num++; aa = setTimeout("startCount()",1000); } </script> </head> <body> <form> <input type="text" id="count" /> <input type="button" onclick="startCount()" value="Start"/> <input type="button" onclick="clearTimeout(aa)" value="Stop"/> </form> </body> </html>
aa = setTimeout("startCount()",1000); // 可以停止
var aa = setTimeout("startCount()",1000); // 报错
如果你没有用var的话,根据js的作用域规则,这个aa变量默认是在最外层(也就是window作用域)定义的.如果你用了var aa 那么这个变量就是在startCount这个函数作用域里面的.clear就获取不到这个变量了,对你有帮助的话,希望采纳
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>计时器</title> <script type="text/javascript"> function clock(){ var time=new Date(); document.getElementById("clock").value = time; } var i=setInterval("clock()",100); </script> </head> <body> <form> <input type="text" id="clock" size="50" /> <input type="button" value="Stop" onclick="clearInterval(i)" /> </form> </body> </html>