JS setInterval() 与 clearInterval() 方法的使用

     setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式。

     clearInterval() 方法可以取消该周期性的方法调用。

    

     详细可参见:http://www.w3school.com.cn/htmldom/met_win_setinterval.asp

 

         当setInterval调用执行完毕时,它将返回一个timer ID,将来便可以利用该值对计时器进行

     访问,如果将该ID传递给clearInterval,便可以终止那段被调用的过程代码的执行了.

 

二、如何使用

    下面的代码体现了以上两个方法的使用方式

 

    1、html页面内容如下:

         ① 页面上用div实时显示当前时间

   ② 调用JS控制div中显示的内容

   ③ 按钮用来停止方法的调用

 

   

[xhtml]  view plain copy
  1. <html>  
  2. <head>  
  3.   <title>标题</title>  
  4.   <script src="../js/clock.js" mce_src="js/clock.js"  
  5.           language="JavaScript">  
  6.   </script>  
  7. </head>  
  8. <body>  
  9.     
  10.   <div id="clock"></div>  
  11.     
  12.   <script language="JavaScript">  
  13.   <!--  
  14.     var clockDiv = document.getElementById("clock");  
  15.       
  16.     // 自定义时钟对象,实时显示当前时间  
  17.     var clickObj = new Clock(clockDiv);  
  18.       
  19.     /*  
  20.      * setInterval()方法使用,周期性的调用clickObj.getCurrentDate()  
  21.      * 以更新显示内容  
  22.       */  
  23.     var intervalId = window.setInterval("clickObj.getCurrentDate()", 1000);  
  24.      
  25.   // -->  
  26.   </script>  
  27.     
  28.   <br>  
  29.     
  30.   <!--   
  31.      此处clearInterval()方法的参数intervalId就是上面setInterval()调用后的  
  32.      返回值   
  33.   -->  
  34.   <input type="button"   
  35.          onclick="window.clearInterval(intervalId)"   
  36.          value="停止计时" />  
  37.     
  38. </body>  
  39. </html>  

 

    2、JS文件(clock.js)内容如下:

   

[javascript]  view plain copy
  1. /* 
  2.  * param clockDiv 
  3.  *      传入的div对象 
  4.  */  
  5. function Clock(clockDiv) {  
  6.       
  7.     this.clockDiv = clockDiv;  
  8.       
  9.     this.getCurrentDate = function() {  
  10.           
  11.         // 获取当前日期  
  12.         var currDate = new Date();  
  13.           
  14.         // 分别获取 年、月、日、时、分、秒  
  15.         var currDateTime = currDate.getYear();  
  16.         currDateTime += "-";  
  17.         currDateTime += (currDate.getMonth() + 1);  
  18.         currDateTime += "-";  
  19.         currDateTime += currDate.getDate();  
  20.         currDateTime += " ";  
  21.         currDateTime += currDate.getHours();  
  22.         currDateTime += ":";  
  23.         currDateTime += currDate.getMinutes();  
  24.         currDateTime += ":";  
  25.         currDateTime += currDate.getSeconds();  
  26.           
  27.         // 将当前时间赋值到div对象中  
  28.         this.clockDiv.innerHTML = currDateTime;  
  29.     }  
  30. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值