這是一個把 setTimeout/clearTimeout 完整跑過一遍的練習:畫面上有一個輸入框顯示當前時間,按「開始」每秒更新,按「結束」停止。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>定時器</title>
<script type="text/javascript">
var timer = null;
function begin() {
var date = new Date();
var current_time = date.getFullYear() + '-'
+ date.getMonth() + '-'
+ date.getDate() + ' ';
current_time += date.getHours() + ':'
+ date.getMinutes() + ':'
+ date.getSeconds();
document.getElementById('current_time').value = current_time;
timer = setTimeout('begin()', 1000);
}
function end() {
clearTimeout(timer); // 清除定時器物件
}
</script>
</head>
<body>
<input type="text" name="current_time" id="current_time"/>
<input type="button" value="開始" onclick="begin();">
<input type="button" value="結束" onclick="end();"><br/>
</body>
</html>
一、setTimeout('begin()', 1000) 的字串寫法。把程式碼寫成字串會觸發 eval,效能差且有注入風險。正確做法是傳函式參照:setTimeout(begin, 1000)。
二、月份要 +1。getMonth() 回傳 0 到 11,所以範例顯示的月份會比實際少一個月。正確寫法是 date.getMonth() + 1。
三、數字沒有補零。8 分 5 秒會顯示成 "8:5",應該是 "08:05":
function pad(n) {
return n < 10 ? '0' + n : '' + n;
}
var current_time = date.getFullYear() + '-'
+ pad(date.getMonth() + 1) + '-'
+ pad(date.getDate()) + ' '
+ pad(date.getHours()) + ':'
+ pad(date.getMinutes()) + ':'
+ pad(date.getSeconds());
四、重複點擊「開始」會排出多條計時鏈。啟動前先清除一次即可:
function begin() {
clearTimeout(timer); // 避免多鏈並行
// ...
}
這個時鐘用「遞迴 setTimeout」而非 setInterval,其實是刻意的選擇。差別在於:setInterval 依固定間隔觸發,不管上一次回呼有沒有跑完;而遞迴 setTimeout 是在上一次執行完畢後才排下一次,因此不會堆積。
這個差異在回呼執行時間可能超過間隔時變得很關鍵——例如每次都做 AJAX 的輪詢。若用 setInterval,慢一次的請求會導致請求堆疊;用遞迴 setTimeout 則天然避免。所以實務上的原則是:要精準的「每 N 秒觸發一次」用 setInterval,要「做完一次,休息 N 秒,再做」用遞迴 setTimeout。