Posted By

pixelatorz on 03/22/12


Tagged

javascript timer


Versions (?)

javascript timer


 / Published in: JavaScript
 

simple html + javascript timer.

  1. /************************************
  2. HTML
  3. ************************************/
  4.  
  5.  
  6. <div id="timer">
  7. <h3>MIJN TIJD</h3>
  8. <div id="minutes">
  9. <div id="m1">0</div>
  10. <div id="m2">0</div>
  11. </div>
  12. <div id="seconds">
  13. <div id="s1">0</div>
  14. <div id="s2">0</div>
  15. </div>
  16. <div id="hundredths">
  17. <div id="h1">0</div>
  18. <div id="h2">0</div>
  19. <div id="h3">0</div>
  20. </div>
  21. </div>
  22.  
  23.  
  24. /************************************
  25. TIMER
  26. ************************************/
  27.  
  28. var startDate;
  29. var intervalId = 0;
  30.  
  31. function startTimer(){
  32. //datum om de vergelijking mee te maken
  33. startDate = new Date();
  34. intervalId = setInterval(setTimer, 11);
  35.  
  36. }
  37.  
  38. function stopTimer(){
  39. clearInterval(intervalId);
  40.  
  41. }
  42.  
  43. function setTimer(){
  44. //hier trekken we de start datum af van de huidige datum om het verschil te krijgen in miliseconden
  45. var currentDate = new Date();
  46. var difference = currentDate - startDate;
  47.  
  48. //console.log(difference);
  49.  
  50. //functie om de tijd terug te geven
  51. formatTime(difference);
  52.  
  53. }
  54.  
  55. function formatTime(ms){
  56.  
  57. //nummers omzetten naar de leesbare getallen
  58. var sec = Math.floor(ms/1000)
  59. ms = ms % 1000
  60. t = three(ms)
  61.  
  62. var min = Math.floor(sec/60)
  63. sec = sec % 60
  64. t = two(sec) + t
  65.  
  66. min = min % 60
  67. t = two(min) + t
  68.  
  69. //console.log(t);
  70. //in een array steken en die reversen om de juiste waarde op te halen
  71. var timeArray = t.split("").reverse();
  72.  
  73. $("#m1").text(timeArray[6]);
  74. $("#m2").text(timeArray[5]);
  75.  
  76. $("#s1").text(timeArray[4]);
  77. $("#s2").text(timeArray[3]);
  78.  
  79. $("#h1").text(timeArray[2]);
  80. $("#h2").text(timeArray[1]);
  81. $("#h3").text(timeArray[0]);
  82.  
  83. }
  84. //plaats een 0 indien de waarde korter dan 2 getallen
  85. function two(x) {return ((x>9)?"":"0")+x}
  86. function three(x) {return ((x>99)?"":"0")+((x>9)?"":"0")+x}

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: DonovanGlover on August 27, 2012

Doesn't work.. http://jsfiddle.net/HLg8R/

Posted By: DonovanGlover on August 27, 2012

nvm, my error..

You need to login to post a comment.