用计时事件创建的时钟

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script>
  5. function startTime() {
  6. var today = new Date();
  7. var h = today.getHours();
  8. var m = today.getMinutes();
  9. var s = today.getSeconds();
  10. m = checkTime(m);
  11. s = checkTime(s);
  12. document.getElementById('txt').innerHTML =
  13. h + ":" + m + ":" + s;
  14. var t = setTimeout(startTime, 500);
  15. }
  16. function checkTime(i) {
  17. if (i < 10) {i = "0" + i}; // 在数字 < 10 之前加零
  18. return i;
  19. }
  20. </script>
  21. </head>
  22.  
  23. <body onload="startTime()">
  24.  
  25. <div id="txt"></div>
  26.  
  27. </body>
  28. </html>