DIV CSS 佈局教程網

JavaScript 計時器 setTimeout 與 setInterval 完整詳解
編輯:JavaScript綜合知識     

延遲執行、週期性刷新、秒表計時——這些都靠 JavaScript 的兩個計時器方法。本文從基本語法一路談到帶參數呼叫的進階技巧,並附可運行的秒表範例。

兩者的差別

  • setTimeout(expression, milliseconds):延遲一段時間後執行一次。
  • setInterval(expression, milliseconds):每隔指定時間重複執行。
  • clearTimeout(id)/clearInterval(id):清除對應的計時器,參數是設定時回傳的 id。

第一個參數可以是字串形式的程式碼,也可以是函數;第二個參數是毫秒數。

基本延遲

<script language="JavaScript" type="text/javascript">
<!--
function hello(){
alert("hello");
}
window.setTimeout(hello,5000);
//-->
</script>

頁面開啟 5 秒後跳出 hello。最後一句也可寫成 window.setTimeout("hello()",5000);,兩者效果相同但字串寫法有求值時機的差異,不建議在新程式碼中使用。

取消延遲

<script>
function hello(){ alert("hello"); }
var id=window.setTimeout(hello,5000);
document.onclick=function(){
  window.clearTimeout(id);
}
</script>

點擊頁面任意處即可取消即將執行的動作。

週期執行與清除

//定義一個反復執行的調用
var id=window.setInterval("somefunction",10000);
//取消定時執行
window.clearInterval(id);

完整範例:0.01 秒精度秒表

<form action="somepage.asp">
<input type="text" value="0" name="txt1"/>
<input type="button" value="開始" name="btnStart"/>
<input type="button" value="重置" name="btnReset"/>
</form>
<script language="JavaScript" type="text/javascript">
<!--
var txt=document.forms[0].elements["txt1"];
var btnStart=document.forms[0].elements["btnStart"];
var btnReset=document.forms[0].elements["btnReset"]
var id;
var seed=0;
btnStart.onclick=function(){
     if(this.value=="開始"){
       this.value="停止";
       btnReset.disabled=true;
       id=window.setInterval(tip,10);
     }else{
       this.value="開始";
       btnReset.disabled=false;
       window.clearInterval(id);
     }
}
btnReset.onclick=function(){
     seed=0;
}
function tip(){
     seed++;
     txt.value=seed/100;
}
//-->
</script>

進階:如何給計時器傳參數

用函數名當句柄時無法帶參數。若寫成 window.setTimeout(hello(userName),3000),函數會立刻執行,回傳值才被當成句柄傳進去——這不是我們要的。字串寫法 window.setTimeout("hello(userName)",3000) 可行,但既不直觀也不安全。技巧是用一個「回傳函數」的外層函數:

var userName="jack";
function hello(_name){
     alert("hello,"+_name);
}
function _hello(_name){
     return function(){
       hello(_name);
     }
}
window.setTimeout(_hello(userName),3000);

_hello(userName) 會回傳一個不帶參數的函數,透過閉包把 userName 夾帶進去,問題就解決了。ES2015 之後更簡潔:setTimeout(() => hello(userName), 3000)。

用 setTimeout 模擬 setInterval

若要在函數末尾再排下一次執行(避免上一次還沒跑完就疊加),可以在函式內部自行遞迴呼叫:

var intvalue=1;
var timer2=null;
function startShow()
{
  liujincai.innerHTML = liujincai.innerHTML + " " + (intvalue++).toString();
  timer2=window.setTimeout("startShow()",2000);
}
function stop()
{
  window.clearTimeout(timer2);
}

或直接用 setInterval 版本:

<input type="button" name="start" value="start" onclick='timer2=window.setInterval("startShow()",2000);'>
<input type="button" name="stop" value="stop" onclick="stop();">
<script>
var intvalue=1;
var timer2=null;
function startShow()
{
 liujincai.innerHTML = liujincai.innerHTML + " " + (intvalue++).toString();
}
function stop()
{
 window.clearInterval(timer2);
}
</script>

實務上一定要知道的事

計時器不保證準時。瀏覽器的 event loop 單執行緒,若主執行緒忙碌,callback 只會延後不會提前。上面的秒表用累加計數的方式,累積誤差會越來越大;正式用途請改用 performance.now() 記錄起點時間再算差值。

間隔太短會拖垮效能。背景分頁更是會被瀏覽器主動降頻(通常限制到 1 秒以上)。setInterval 也記得在元件卸載或頁面離開時清除,否則容易造成記憶體與 CPU 洩漏。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved