看下面的一个javascript写的小时钟:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> </head> <body > <form name="clock"> <input type="text" name="clockpanel" value="" /> <br/> <input type="button" name="startBt" value="start" /> <input type="button" name="stopBt" value="stop" /> </form> <script type="text/javascript"> var timerID=null; var timerRunning=false; var id,pause=0,position=0; function stopClock() { if(timerRunning) { clearTimeout(timerID); timerRunning=false; } } function showTime() { var now=new Date(); var hours=now.getHours(); var minutes=now.getMinutes(); var seconds=now.getSeconds(); var timeValue=" "+((hours>12)?hours-12:hours); timeValue+=((minutes<10)?":0": ":")+minutes; timeValue+=((seconds<10)?":0": ":")+seconds; timeValue+=((hours>=12)?" P.M":" A.M"); document.forms.clock.clockpanel.value=timeValue; timeID=setTimeout('showTime()',1000); console.log(timeID); timerRunning=true; } function startClock() { stopClock(); showTime(); } var startButton=document.forms.clock.startBt; var stopButton=document.forms.clock.stopBt; startButton.addEventListener('click',startClock,false); stopButton.addEventListener('click',stopClock,false); </script> </body> </html>
点击开始按钮就开始计数,可是点击stop没有反应,为什么?
另外一个clock:
<html> <head> <script type="text/javascript"> var c=0 var t function timedCount() document.getElementById('txt').value=c { c=c+1 t=setTimeout("timedCount()",1000) } function stopCount() { clearTimeout(t) } </script> </head> <body>时!" onClick="timedCount()"> <input type="text" id="txt"> <form> <input type="button" value="开始计 <input type="button" value="停止计时!" onClick="stopCount()"> </form> <p> 请点击上面的“开始计时”按钮。输入框会从 0 开始一直进行计时。点击“停止计时”可停止计时。 </p> </body> </html>
demo:http://www.w3school.com.cn/tiy/t.asp?f=hdom_timing_stop