<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>计时器</title> <script type="text/javascript"> var i; function clock(){ var time=new Date(); document.getElementById("clock").value = time.getHours()+":"+time.getMinutes()+":"+time.getSeconds(); } //i=setInterval(clock,1000); function start(){ i=setInterval("clock()",1000); } function stop(){ clearInterval(i); } </script> </head> <body> <form> <input type="text" id="clock" size="50" /> <input type="button" value="Start" onclick="start()"/> <input type="button" value="Stop" onclick="stop()"/> </form> </body> </html>
一个是事件绑定机制,另一个则是点击触发stop()清除了定时器,clock()函数停止了每隔一秒的自动执行。