定时器的制作与清除

 1 <HTML>
 2 <HEAD>
 3 <META http-equiv="Content-Type" content="text/html; charset=gb2312">
 4 <TITLE>无标题文档</TITLE>
 5 <STYLE type="text/css">
 6 <!--
 7 /*设置样式:无边框的文本框*/
 8 INPUT {
 9     font-size: 20px;
10     border-style:none ;
11     background-color:#FF8B3B;
12     color:#E7E5E5;
13     }
14 -->
15 </STYLE>
16 <SCRIPT language="javascript" type="text/javascript" >
17 var id=null;
18 function reloop(){
19      var time = new Date( ); //获得当前时间
20      //获得小时、分钟、秒
21      var hour = time.getHours();  
22      var minute = time.getMinutes();
23      var second = time.getSeconds();
24      if (minute < 10) //如果分钟只有1位,补0显示
25        minute="0"+minute;
26      if (second < 10) //如果秒数只有1位,补0显示
27         second="0"+second;
28     document.getElementById("t").value=hour+":"+minute+":"+second;
29     id=setTimeout("reloop()",1000);
30     
31 }
32 window.onload=function(){
33     var btn=document.getElementById('btn'); 
34     btn.onclick=function(){
35          if(this.value=="开始"){  
36                   //使按钮文本变为停止  
37                   this.value="停止"; 
38                   this.innerHTML= "停止";
39                   //设置定时器,每1s跳一次
40                   id=window.setTimeout("reloop()",1000);    
41           }else{  
42                   //使按钮文本变为开始  
43                   this.value="开始";
44                   this.innerHTML="开始";
45                   //取消定时  
46                   window.clearTimeout(id);  
47           } 
48     }
49     reloop();
50 }
51 </SCRIPT>
52 
53 </HEAD>
54 
55 <BODY>
56 现在时间:<INPUT id="t" name="time" type="text" size="10">
57 <button id="btn" value="停止">停止</button>
58 </BODY>
59 </HTML>
View Code
原文地址:https://www.cnblogs.com/dashen/p/3895668.html