随手写个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>