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>

 


免責聲明!

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



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