萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

原生 JavaScript 實現驗證碼倒數計時按鈕 (防重複發送)

核心需求

用戶點擊「獲取驗證碼」→ 按鈕禁用並顯示倒計時 (如「60秒後重新發送」)→ 倒計時結束恢復可點擊狀態。防止短信/郵件接口被濫用。

方案一:遞歸 setTimeout (經典寫法)

<input type="button" id="btn" value="免費獲取驗證碼" onclick="settime(this)" />

<script>
var countdown = 60;
function settime(btn) {
    if (countdown === 0) {
        btn.removeAttribute("disabled");
        btn.value = "免費獲取驗證碼";
        countdown = 60;
        return;
    }
    btn.setAttribute("disabled", "disabled");
    btn.value = "重新發送(" + countdown + ")";
    countdown--;
    setTimeout(function() { settime(btn); }, 1000);
}
</script>

方案二:setInterval + 狀態變數 (更易控制)

<input type="button" id="btn" value="免費獲取驗證碼" />

<script>
var wait = 60;
var timer = null;
var btn = document.getElementById('btn');

btn.onclick = function() {
    if (timer) return; // 防止重複點擊
    timer = setInterval(function() {
        if (wait === 0) {
            btn.removeAttribute("disabled");
            btn.value = "免費獲取驗證碼";
            wait = 60;
            clearInterval(timer);
            timer = null;
        } else {
            btn.setAttribute("disabled", "disabled");
            btn.value = wait + "秒後可以重新發送";
            wait--;
        }
    }, 1000);
};
</script>

方案三:現代 ES6 封裝類 (可復用、多實例)

class CountdownButton {
    constructor(buttonEl, options = {}) {
        this.btn = buttonEl;
        this.seconds = options.seconds || 60;
        this.onText = options.onText || "免費獲取驗證碼";
        this.offText = options.offText || "{sec}秒後重新發送";
        this.onClick = options.onClick || (() => {}); // 實際發送驗證碼邏輯
        this.timer = null;
        this.remaining = this.seconds;
        this.btn.addEventListener('click', this.handleClick.bind(this));
    }

    handleClick() {
        if (this.timer) return;
        this.onClick().then(() => this.startCountdown()).catch(() => {
            // 發送失敗:立即恢復
            this.reset();
        });
    }

    startCountdown() {
        this.btn.disabled = true;
        this.updateText();
        this.timer = setInterval(() => {
            this.remaining--;
            if (this.remaining <= 0) this.reset();
            else this.updateText();
        }, 1000);
    }

    updateText() {
        this.btn.value = this.offText.replace('{sec}', this.remaining);
    }

    reset() {
        clearInterval(this.timer);
        this.timer = null;
        this.remaining = this.seconds;
        this.btn.disabled = false;
        this.btn.value = this.onText;
    }

    destroy() {
        this.reset();
        this.btn.removeEventListener('click', this.handleClick.bind(this));
    }
}

// 使用
new CountdownButton(document.getElementById('btn'), {
    seconds: 60,
    onClick: () => fetch('/api/send-sms', {method:'POST', body:JSON.stringify({phone: '13800000000'})})
        .then(r => r.ok ? Promise.resolve() : Promise.reject())
});

後端配合:真正防刷

前端倒計時**只能阻擋誠實用戶**,惡意腳本可繞過。必須在後端實施:

  • **頻率限制**:同一手機號/IP 每分鐘/小時/天發送上限 (Redis 計數器)。
  • **圖形/行為驗證碼**:發送前需通過滑塊、點選文字等人機驗證。
  • **驗證碼有效期**:5~10 分鐘,錯誤 5 次鎖定。
  • **日誌審計**:記錄發送請求、IP、User-Agent、設備指紋。

無障礙 (a11y) 增強

<button id="btn" aria-live="polite">免費獲取驗證碼</button>

JS 中更新 `btn.textContent` 即可自動播報。

copyright © 萬盛學電腦網 all rights reserved