js计时函数实现秒表的开始-暂停-清零功能
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body>
8 <h1>在页面上实现一个秒表 00:00:00 (分钟:秒钟:百分秒) ,通过三个按钮(开始、停止、重置)来控制</h1> 9 <p id="second_watch">00:00:00</p> 10 <p> 11 <input id="time_start" type="button" value="开始" onclick="time_start()" /> 12 <input type="button" value="停止" onclick="time_stop()" /> 13 <input type="button" value="重置" onclick="time_reset()" /> 14 </p>
15 <script> 16 var i1 = 0; //分钟第一位 17 var i2 = 0; //分钟第二位 18 var s1 = 0; //秒第一位 19 var s2 = 0; //秒第二位 20 var ms1 = 0; //百分秒第一位 21 var ms2 = 0; //百分秒第二位 22 var t; //计时函数保存 23 function time_start(){ 24 document.getElementById("time_start").disabled = "true"; //开始后使开始按钮失效,防止多次点击计时加快的bug 25 ms2++; //只需百分秒最后一位自加,前面依次进位 26 if(ms2>9){ 27 ms2 = 0; 28 ms1++; 29 } 30 if(ms1>9){ 31 ms1 = 0; 32 s2++; 33 } 34 if(s2>9){ 35 s2 = 0; 36 s1++; 37 } 38 if(s1>5){ 39 s1 = 0; 40 i2++; 41 } 42 if(i2>9){ 43 i2 = 0; 44 i1++; 45 } 46 if(i1>5){ 47 //超出秒表计数范围 48 clearTimeout(t); 49 return false; 50 } 51 document.getElementById("second_watch").innerHTML = ""+i1+i2+":"+s1+s2+":"+ms1+ms2+""; 52 document.getElementById("second_watch").style.color = "black"; 53 t = setTimeout("time_start()",10); //百分秒百分之一秒执行一次 54 } 55 56 function time_stop(){ 57 clearTimeout(t); 58 document.getElementById("second_watch").style.color = "red"; 59 document.getElementById("time_start").disabled = ""; //停止时恢复按钮功能 60 } 61 62 function time_reset(){ 63 clearTimeout(t); 64 i1 = 0; 65 i2 = 0; 66 s1 = 0; 67 s2 = 0; 68 ms1 = 0; 69 ms2 = 0; 70 document.getElementById("second_watch").innerHTML = ""+i1+i2+":"+s1+s2+":"+ms1+ms2+""; 71 document.getElementById("second_watch").style.color = "black"; 72 document.getElementById("time_start").disabled = ""; 73 } 74 75 </script> 76 </body> 77 </html>