按鈕點擊觸發功能,需限制 **2 秒內不得重複點擊**,防止重複提交/請求。
let clickAllowed = true; // 閉包/模塊級變量
function handleClick() {
if (!clickAllowed) return; // 冷卻中直接返回
clickAllowed = false; // 進入冷卻
// 業務邏輯
doSomething();
// 2 秒後恢復
setTimeout(() => { clickAllowed = true; }, 2000);
}
// 綁定
document.getElementById('btn').addEventListener('click', handleClick);
// 防抖:延遲執行,若冷卻內再次觸發則重置計時器
function debounce(fn, delay) {
let timer = null;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
// 節流:固定間隔只執行一次
function throttle(fn, interval) {
let last = 0;
return function(...args) {
const now = Date.now();
if (now - last >= interval) {
last = now;
fn.apply(this, args);
}
};
}
// 使用
const safeClick = throttle(doSomething, 2000);
btn.addEventListener('click', safeClick);
disabled 狀態,顯示倒計時文字:「2s 後可再次點擊」。cursor: not-allowed; opacity: 0.6; 視覺提示不可用。disabled,文字還原。| 模式 | 行為 | 典型場景 |
|---|---|---|
| 標誌+setTimeout | 冷卻期內完全忽略點擊 | 表單提交、支付、刪除等**冪等性敏感**操作 |
| 節流 throttle | 固定間隔執行最新一次 | 搜索聯想、窗口 resize、滾動加載 |
| 防抖 debounce | 停止觸發 N 秒後執行最後一次 | 輸入框實時驗證、自動保存 |
按鈕防重複提交,**標誌變量 + setTimeout 最直觀可靠**;配合 UI 禁用狀態,用戶體驗最佳。