setTimeout和setInterval

setTimeout(methodName, interval); //间隔时间单位为毫秒,表示interval毫秒后执行方法methodName

setInterval(methodName, interval); //间隔时间单位为毫秒,表示每隔interval毫秒执行后都会执行一次方法methodName

执行的方法可以带参数,但是参数只能是字符串、数字类的,不能是对象

实例代码:

 1 <html>
 2     <head>
 3         <title>标题</title>
 4         <meta charset="utf8"/>
 5         <script type="text/javascript">
 6             //测试setTimeout
 7             var runTimeout, runInteval;
 8             function TestTimeout(idName){
 9                 if (!idName) idName = "showInfo";
10                 
11                 document.getElementById(idName).innerText = (new Date()) + ", runTimeout = " + runTimeout;
12                 runTimeout = setTimeout("TestTimeout('showInfo')", 1000); //一秒后执行
13                 //或者写作:runTimeout = setTimeout(TestTimeout, 1000); //一秒后执行
14             }
15 
16             function TestClearTimeout(){
17                 clearTimeout(runTimeout);
18                 runTimeout = null;
19                 document.getElementById("showInfo").innerText = "setTimeout()停止了,  runTimeout = " + runTimeout;
20             }
21 
22             //测试setInterval
23             function ChangeTime(idName){
24                 document.getElementById(idName).innerText = (new Date()) + ", runInteval = " + runInteval + ", runTimeout = " + runTimeout;
25             }
26 
27             function TestInterval(){
28                 if (runInteval){
29                     return;
30                 }
31                 runInteval = setInterval("ChangeTime('showInfo2')", 1000); //每过一秒就调用ChangeTime()方法
32                 //或者写作:runInteval = setInterval(ChangeTime, 1000);//需要带参数的话就用上面那种写法
33             }
34             //停止setInterval
35             function TestClearInterval(){
36                 clearInterval(runInteval);
37                 runInteval = null;
38                 document.getElementById("showInfo2").innerText = "setInterval()停止了,  runInteval = " + runInteval;
39             }
40 
41 
42         </script>
43     </head>
44     <body>
45         <h3 id="showInfo"></h3>
46         <h3 id="showInfo2"></h3>
47         <input type="button" value="测试timeout" onclick="TestTimeout()"/>
48         <input type="button" value="停止timeout" onclick="TestClearTimeout()"/>
49         <input type="button" value="测试interval" onclick="TestInterval()"/>
50         <input type="button" value="停止interval" onclick="TestClearInterval()" />
51     </body>
52 </html>
View Code

 

posted @ 2015-05-28 21:42  谈晓鸣  阅读(292)  评论(0编辑  收藏  举报