1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>动态时钟</title> 6 <style> 7 p { 8 border: 1px solid red; 9 width: 200px; 10 height: 30px; 11 line-height: 30px; 12 text-align: center; 13 } 14 </style> 15 <script> 16 var id; 17 function start() { 18 //若id非空,则定时器已启动,不必再次启动了. 19 if(id) { 20 return; 21 } 22 id = setInterval(function(){ 23 var date = new Date(); 24 var time = date.toLocaleTimeString(); 25 var p = document.getElementById("clock"); 26 p.innerHTML = time; 27 },1000); 28 } 29 function stop() { 30 clearInterval(id); 31 //停止定时器时清空id,以便于下次启动. 32 id = null; 33 } 34 </script> 35 </head> 36 <body> 37 <input type="button" value="开始" onclick="start();"/> 38 <input type="button" value="停止" onclick="stop();"/> 39 <p id="clock"></p> 40 </body> 41 </html>