先上代码
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <script> 5 function startTime() 6 { 7 var today=new Date(); 8 var h=today.getHours(); 9 var m=today.getMinutes(); 10 var s=today.getSeconds(); 11 // add a zero in front of numbers<10 12 m=checkTime(m); 13 s=checkTime(s); 14 document.getElementById('txt').innerHTML=h+":"+m+":"+s; 15 t=setTimeout(function(){startTime()},500); 16 } 17 18 function checkTime(i) 19 { 20 if (i<10) 21 { 22 i="0" + i; 23 } 24 return i; 25 } 26 </script> 27 </head> 28 29 <body onload="startTime()"> 30 <div id="txt"></div> 31 </body> 32 </html>
核心方法: setTimeout
这个方法规定了以某个时间间隔执行某个事件或函数,和oc的NSTimer很像