javascript 秒表計時器


隨手寫個js計時器,非常簡單的,但是一些邏輯處理感覺還是有點怪怪的...

不知道怎么把那個時間格式顯示為00:00:00:00的樣子,使用checkTime() 將會產生一大串0,is anybody help me ?

效果如下圖

  1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2 <html xmlns="http://www.w3.org/1999/xhtml">
  3 <head>
  4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5 <title>簡單的計時器</title>
  6 </head>
  7 
  8 <body>
  9 <input type="button" id="start" onclick="startTime()" value="開始計時"/>
 10 <input type="button" id="stop" onclick="stopTime()" value="停止"/>
 11 <input type="button" onclick="clearTime()" value="清零"/>
 12 <p id="showTime">00 : 00 : 00 : 00</p>
 13 <script>
 14     var ms = 0;
 15     var secs = 0;
 16     var mins = 0;
 17     var hours = 0;
 18     var timeoutId;
 19 
 20 var isCounting = false;    
 21 
 22 function startTime()
 23 {    
 24     if(!isCounting)
 25     {
 26         isCounting = true;
 27         timeoutId = setInterval(countTime,1);        //指定時間執行任務
 28     }
 29 
 30     document.getElementById("start").value = "計時中";
 31 }
 32 
 33 function stopTime()
 34 {
 35     if(isCounting)
 36     {
 37         isCounting = false;
 38         clearTimeout(timeoutId); //清除指定id計時器
 39         document.getElementById("start").value = "繼續";
 40     }
 41 }
 42 
 43 function countTime()
 44 {
 45     ms+=1;
 46     if(ms>=100)
 47     {
 48         secs+=1;
 49         ms = 0;
 50     }
 51     if(secs>=60)
 52     {
 53         mins+=1;    
 54         secs = 0;
 55     }
 56     if(mins>=60)
 57     {
 58         hours+=1;
 59         mins = 0;    
 60     }
 61     if(hours>=24)
 62     {
 63         hours = 0;
 64     }
 65     
 66 //    ms = checkTime(ms);
 67 //    secs = checkTime(secs);
 68 //    mins = checkTime(mins);
 69 //    hours = checkTime(hours);
 70         
 71         
 72     document.getElementById("showTime").innerHTML = hours + " : " + mins + " : " + secs + " : " + ms;
 73 }
 74 
 75 function checkTime(time)
 76 {
 77     if(time<10)
 78         time = "0"+time;
 79     
 80     return time;
 81 }
 82 function resetTime()
 83 {
 84     ms = 0;
 85     secs = 0;
 86     mins = 0;
 87     hours = 0;        
 88     
 89 }
 90 function clearTime()
 91 {
 92     resetTime();
 93     document.getElementById("showTime").innerHTML = hours + " : " + mins + " : " + secs + " : " + ms;
 94     if(!isCounting)
 95         document.getElementById("start").value = "開始計時";
 96 }
 97 
 98 
 99 </script>
100 </body>
101 </html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM