setTimeout和setInterval

setTimeout(methodName, interval); //間隔時間單位爲毫秒,表示interval毫秒後執行方法methodNamejavascript

setInterval(methodName, interval); //間隔時間單位爲毫秒,表示每隔interval毫秒執行後都會執行一次方法methodNamehtml

執行的方法能夠帶參數,可是參數只能是字符串、數字類的,不能是對象java

實例代碼:ide

 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
相關文章
相關標籤/搜索