aviel900

Simple Stopwatch

Sep 17th, 2019
608
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 1.20 KB | None | 0 0
  1. <html>
  2.  <head>
  3.   <title>Simple Stopwatch</title>
  4.  </head>
  5.  <body>
  6.   <h1><time>00:00:00</time></h1>
  7.   <button id="start">start</button>
  8.   <button id="stop">stop</button>
  9.   <button id="clear">clear</button>
  10.   <script>
  11.    var h1 = document.getElementsByTagName('h1')[0],
  12.     start = document.getElementById('start'),
  13.     stop = document.getElementById('stop'),
  14.     clear = document.getElementById('clear'),
  15.     seconds = 0, minutes = 0, hours = 0,
  16.     t;
  17.  
  18. function add() {
  19.     seconds++;
  20.     if (seconds >= 60) {
  21.         seconds = 0;
  22.         minutes++;
  23.         if (minutes >= 60) {
  24.             minutes = 0;
  25.             hours++;
  26.         }
  27.     }
  28.    
  29.     h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
  30.  
  31.     timer();
  32. }
  33. function timer() {
  34.     t = setTimeout(add, 1000);
  35. }
  36. timer();
  37.  
  38.  
  39. /* Start button */
  40. start.onclick = timer;
  41.  
  42. /* Stop button */
  43. stop.onclick = function() {
  44.     clearTimeout(t);
  45. }
  46.  
  47. /* Clear button */
  48. clear.onclick = function() {
  49.     h1.textContent = "00:00:00";
  50.     seconds = 0; minutes = 0; hours = 0;
  51. }
  52.   </script>
  53.  </body>
  54. </html>
Add Comment
Please, Sign In to add comment