萬盛學電腦網

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

JavaScript 按鈕點擊後倒數計時防重複提交完整實作

應用場景

發送驗證碼、提交表單、付款等操作需防止使用者短時間內重複點擊,導致重複請求或資源浪費。標準做法:點擊後按鈕禁用並顯示倒數,時間到自動恢復。

基礎版實作(原文重構)

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>按鈕倒數計時防重複提交</title>
    <style>
        .btn { padding: 10px 20px; font-size: 16px; cursor: pointer; }
        .btn:disabled { background: #ccc; color: #666; cursor: not-allowed; }
    </style>
</head>
<body>
    <button id="btnSendCode" class="btn">免費獲取驗證碼</button>

    <script>
        var wait = 60; // 倒數秒數
        var btn = document.getElementById('btnSendCode');

        function countdown(button) {
            if (wait === 0) {
                button.disabled = false;
                button.textContent = '免費獲取驗證碼';
                wait = 60; // 重置供下次使用
            } else {
                button.disabled = true;
                button.textContent = wait + ' 秒後可重新發送';
                wait--;
                setTimeout(function() { countdown(button); }, 1000);
            }
        }

        btn.onclick = function() {
            countdown(this);
            // 這裡放入實際發送驗證碼的 Ajax 呼叫
            // sendSmsCode().catch(() => { wait = 0; countdown(btn); }); // 失敗時立即恢復
        };
    </script>
</body>
</html>

進階版:支援多按鈕、Promise 整合、狀態管理

class ButtonCooldown {
    constructor(button, seconds = 60, options = {}) {
        this.button = button;
        this.seconds = seconds;
        this.remaining = seconds;
        this.originalText = button.textContent;
        this.disabledClass = options.disabledClass || 'btn-disabled';
        this.onCooldownEnd = options.onCooldownEnd || (() => {});
        this.timer = null;
    }

    start(asyncAction) {
        if (this.timer) return; // 防止重複啟動
        this.button.disabled = true;
        this.button.classList.add(this.disabledClass);
        this.tick();

        // 若提供 asyncAction(回傳 Promise),等待完成才開始倒數
        // 適合「點擊 -> 發送請求 -> 成功才開始倒數」的流程
        if (asyncAction && typeof asyncAction.then === 'function') {
            asyncAction
                .then(() => this.startCountdown())
                .catch(() => this.reset()); // 失敗立即恢復
        } else {
            this.startCountdown();
        }
    }

    startCountdown() {
        this.timer = setInterval(() => {
            this.remaining--;
            this.button.textContent = this.remaining + ' 秒後可重試';
            if (this.remaining <= 0) this.stop();
        }, 1000);
    }

    tick() {
        // 立即顯示初始倒數
        this.button.textContent = this.remaining + ' 秒後可重試';
    }

    stop() {
        clearInterval(this.timer);
        this.timer = null;
        this.reset();
        this.onCooldownEnd();
    }

    reset() {
        this.remaining = this.seconds;
        this.button.disabled = false;
        this.button.classList.remove(this.disabledClass);
        this.button.textContent = this.originalText;
    }
}

// 使用範例
document.querySelectorAll('.btn-cooldown').forEach(btn => {
    const cooldown = new ButtonCooldown(btn, 60, {
        onCooldownEnd: () => console.log('冷卻結束')
    });
    btn.addEventListener('click', () => {
        cooldown.start(fetch('/api/send-code', { method: 'POST' }));
    });
});

關鍵最佳實務

原則說明
前端攔截 + 後端冪等前端防呆體驗佳,但必須配合後端冪等設計(如 Token、去重鍵),防止繞過前端或網路重試。
失敗即時恢復Ajax 失敗(網路錯誤、後端 5xx)應立即 wait = 0 恢復按鈕,避免使用者卡死。
避免全域變數污染使用閉包、Class 或 data-* 屬性儲存狀態,支援頁面多按鈕共存。
無障礙支援加上 aria-disabled="true"、aria-live="polite" 讓螢幕閱讀器播報倒數狀態。

Vue / React 元件化參考

<!-- Vue 3 Composition API -->
<script setup>
import { ref } from 'vue';
const seconds = ref(0);
const originalText = ref('發送驗證碼');

function startCooldown() {
    seconds.value = 60;
    const timer = setInterval(() => {
        seconds.value--;
        if (seconds.value <= 0) clearInterval(timer);
    }, 1000);
}

function handleClick() {
    if (seconds.value > 0) return;
    sendCodeApi().then(startCooldown).catch(() => { seconds.value = 0; });
}
</script>

<template>
<button :disabled="seconds > 0" @click="handleClick">
    {{ seconds > 0 ? seconds + ' 秒後可重試' : originalText }}
</button>
</template>

總結

按鈕倒數防重複是前端基礎體驗優化。基礎版適合簡單頁面,進階 Class 版適合專案化復用,現代框架下建議封裝為可複用元件。核心三要素:即時禁用、視覺倒數、失敗恢復,並務必配合後端冪等機制。

copyright © 萬盛學電腦網 all rights reserved