JavaScript 提供兩種定時機制:一次性延遲 (setTimeout) 與 週期性重複 (setInterval),並對應兩種清除方法。本文詳細說明語法、參數傳遞、取消機制、秒表實作與參數傳遞技巧。
// 一次性延遲
var timeoutId = setTimeout(functionRef, milliseconds);
// 或
var timeoutId = setTimeout("code string", milliseconds);
// 週期性重複
var intervalId = setInterval(functionRef, milliseconds);
// 或
var intervalId = setInterval("code string", milliseconds);
// 取消
clearTimeout(timeoutId);
clearInterval(intervalId);
setTimeout("hello('jack')", 3000) — 簡單但類 eval,不推薦。setTimeout(function(){ hello('jack'); }, 3000) — 最常用、支援閉包。function _hello(name) {
return function() { hello(name); };
}
setTimeout(_hello('jack'), 3000);
文章提供完整 HTML + JS 碼錶:開始/停止按鈕切換、重置歸零、setInterval(tip, 10) 每 10ms 更新顯示。展開程式碼見原文。
setTimeout(fn(i), 100) 會立即執行;需用閉包或 let (ES6) 解決。alert() 會阻塞主執行緒,導致 setTimeout 計時暫停(見另一篇文章)。clearInterval。