<script>
function myFunction() {
alert("click");
var zh = setTimeout("myFunction()", 2000); // zh 為局部變量!
}
function temp() {
clearTimeout(zh); // 錯誤:zh 不在作用域內,實際操作全局 zh(undefined)
}
</script>
現象:點擊「取消」按鈕後,彈窗仍每 2 秒彈出一次。
var zh 定義在 myFunction 內部 → **函數作用域**,外部函數 temp 不可見。temp 中引用 zh 時,若全局無同名變量 → ReferenceError(嚴格模式)或操作 undefined(非嚴格),clearTimeout(undefined) 無效。var zh,myFunction 內部 var zh 會**遮蔽**全局變量,導致定時器 ID 存入局部變量,全局變量仍為 undefined。<script>
var timerId = null; // 全局/模塊作用域
function startLoop() {
alert("click");
timerId = setTimeout(startLoop, 2000); // 直接賦值給全局變量
}
function stopLoop() {
if (timerId !== null) {
clearTimeout(timerId);
timerId = null;
}
}
</script>
const timerController = (() => {
let id = null;
return {
start: () => { alert("click"); id = setTimeout(() => timerController.start(), 2000); },
stop: () => { if (id) { clearTimeout(id); id = null; } }
};
})();
// 使用:timerController.start() / timerController.stop()
var/let/const 重新聲明變量,直接賦值給外層變量。setTimeout("string") 的 eval 風險與 this 綁定問題。掌握「作用域鏈 + 定時器 ID 生命週期」,輕鬆破解各類定時器無法清除的疑難雜癥。