js中setTimeout()的用法
setTimeout() 是屬於 window 的方法,該方法用於在指定的毫秒數后調用函數或計算表達式。
語法格式可以是以下兩種:
setTimeout(要執行的代碼, 等待的毫秒數)
setTimeout(JavaScript 函數, 等待的毫秒數)
setTimeout()方法就是在指定的毫秒數后調用一段代碼或者一條函數。在看了一些博客后看到,竟然有的博客說,setTimeout可以
setTimeout 在執行時,它從載入后,每隔指定的時間就執行一次表達式(打地鼠中的地鼠的出現)
實踐上是函數用一種方式實現了定時器的效果,就像用if語句實現了for循環的效果
x = 0
function countSecond()
{
x = x+1
document.getElementById("displayBox").value=x
setTimeout("countSecond()", 1000)
}
// 執行函數
countSecond()
這是官方文檔給出定時器的代碼
真正的定時器應該是window.setTimeout(expression,millisec);
JS定時器 setInterval() 方法: 使一段代碼每過指定時間就運行一次。
JS延遲器 setTimeout() 方法:使一段代碼在指定時間后運行。
定義:
window.setInterval(expression,millisec); window.setTimeout(expression,millisec);
參數介紹:
expression:可以是用引號括起來的一段代碼,也可以是一個函數名,當使用函數名作為調用句柄時,不能帶有任何參數;而使用字符串時,則可以在其中寫入要傳遞的參數。
millisec:表示重復執行或者延時的毫秒數。1000毫秒=1秒
使用函數名方式:setInterval(hello,1000); //不能帶有任何參數
使用字符串方式:setInterval("hello()",1000); //可以在其中寫入要傳遞的參數
定義對象:
var id=window.setInterval("hello()",1000); var id=window.setTimeout("hello()",1000);
**清除對象:
**
window.clearInterval(id); //清除已設置的setInterval對象 window.clearTimeout(id); //清除已設置的setTimeout對象
實例1:使用 clearInterval
<input type="text" id="clock" size="35" /><script language="JavaScript" type="text/javascript"> window.setInterval("clock()",50)function clock(){ document.getElementById("clock").value=new Date()}</script>
實例2:使用 setTimeout
<script language="JavaScript" type="text/javascript"> function hello(){ alert("hello"); } window.setTimeout(hello,5000); </script>
實例3:使用 clearInterval ,定義對象和清除對象使用
<input type="text" id="clock" size="35" /><script language="JavaScript" type="text/javascript"> var int=self.setInterval("clock()",50)function clock(){ document.getElementById("clock").value=new Date()}</script><button onclick="int=window.clearInterval(int)">Stop interval</button>
實例4:使用 clearTimeout,定義對象和清除對象使用
<script language="JavaScript" type="text/javascript"> function hello(){ alert("hello"); }var id=window.setTimeout(hello,5000); document.onclick=function(){ window.clearTimeout(id); } </script>
實例5:使用 clearTimeout,有參數傳遞
<script language= "JavaScript" type="text/javascript"> function timedMsg(){ var t=setTimeout("alert('1 seconds!')",1000)}</script><input type="button" value="顯示計時的消息框!" onClick = "timedMsg()">
clearTimeout函數執行就是阻止 setTimeout函數的執行,詳細點理解,在進行計時器是如果clear計時器就停止,在點擊計時時重新計時,從原來的數字
