class CountdownButton {
constructor(buttonEl, options = {}) {
this.btn = buttonEl;
this.seconds = options.seconds || 60;
this.originalText = options.originalText || this.btn.textContent;
this.countdownText = options.countdownText || '重新發送({{s}})';
this.onStart = options.onStart; // 返回 Promise,resolve 繼續倒計時,reject 取消
this.onEnd = options.onEnd;
this.timer = null;
this.remaining = 0;
this.bindEvents();
}
bindEvents() {
this.btn.addEventListener('click', this.handleClick.bind(this));
}
async handleClick() {
if (this.isCounting) return;
this.btn.disabled = true;
this.btn.setAttribute('aria-busy', 'true');
try {
if (this.onStart) await this.onStart(); // 執行發送驗證碼等異步操作
this.startCountdown();
} catch (err) {
this.reset();
throw err;
}
}
startCountdown() {
this.remaining = this.seconds;
this.updateText();
this.timer = setInterval(() => {
this.remaining--;
this.updateText();
if (this.remaining <= 0) this.stopCountdown();
}, 1000);
}
updateText() {
this.btn.textContent = this.countdownText.replace('{{s}}', this.remaining);
}
stopCountdown() {
clearInterval(this.timer);
this.timer = null;
this.reset();
this.onEnd?.();
}
reset() {
this.btn.disabled = false;
this.btn.removeAttribute('aria-busy');
this.btn.textContent = this.originalText;
}
get isCounting() { return !!this.timer; }
}
// 使用
const btn = document.getElementById('getCodeBtn');
const countdownBtn = new CountdownButton(btn, {
seconds: 60,
originalText: '獲取驗證碼',
countdownText: '{{s}}s 後重試',
onStart: () => fetch('/api/send-sms', {method: 'POST', body: JSON.stringify({phone: '13800000000'})})
.then(r => { if (!r.ok) throw new Error('發送失敗'); })
});
class PersistentCountdownButton extends CountdownButton {
constructor(buttonEl, options = {}) {
super(buttonEl, {...options, onStart: undefined}); // 不自動觸發 onStart
this.storageKey = options.storageKey || `countdown_${buttonEl.id}`;
this.restoreState();
}
restoreState() {
const data = JSON.parse(localStorage.getItem(this.storageKey) || '{}');
if (data.endTime && data.endTime > Date.now()) {
this.remaining = Math.ceil((data.endTime - Date.now()) / 1000);
this.btn.disabled = true;
this.btn.setAttribute('aria-busy', 'true');
this.updateText();
this.timer = setInterval(() => {
this.remaining--;
this.updateText();
if (this.remaining <= 0) this.stopCountdown();
}, 1000);
}
}
startCountdown() {
super.startCountdown();
const endTime = Date.now() + this.seconds * 1000;
localStorage.setItem(this.storageKey, JSON.stringify({endTime}));
}
stopCountdown() {
super.stopCountdown();
localStorage.removeItem(this.storageKey);
}
}
aria-busy="true":告知螢幕閱讀器正在處理中aria-live="polite":倒計時數字變化自動播報
<script setup>
import {ref, onUnmounted} from 'vue';
const props = defineProps({
seconds: {type: Number, default: 60},
originalText: {type: String, default: '獲取驗證碼'},
countdownText: {type: String, default: '{{s}}s 後重試'},
onStart: {type: Function, required: true}
});
const counting = ref(false);
const remaining = ref(0);
let timer = null;
const start = async () => {
if (counting.value) return;
counting.value = true;
try {
await props.onStart();
remaining.value = props.seconds;
timer = setInterval(() => {
remaining.value--;
if (remaining.value <= 0) stop();
}, 1000);
} catch (e) {
counting.value = false;
}
};
const stop = () => {
clearInterval(timer);
timer = null;
counting.value = false;
};
onUnmounted(() => clearInterval(timer));
</script>
<template>
<button
:disabled="counting"
:aria-busy="counting"
aria-live="polite"
@click="start"
>
{{ counting ? countdownText.replace('{{s}}', remaining) : originalText }}
</button>
</template>
function useCountdownButton({seconds = 60, onStart, onEnd}) {
const [counting, setCounting] = useState(false);
const [remaining, setRemaining] = useState(0);
const timerRef = useRef(null);
const start = useCallback(async () => {
if (counting) return;
setCounting(true);
try {
await onStart();
setRemaining(seconds);
timerRef.current = setInterval(() => {
setRemaining(r => {
if (r <= 1) { stop(); return 0; }
return r - 1;
});
}, 1000);
} catch (e) {
setCounting(false);
}
}, [counting, seconds, onStart]);
const stop = useCallback(() => {
clearInterval(timerRef.current);
timerRef.current = null;
setCounting(false);
onEnd?.();
}, [onEnd]);
useEffect(() => () => clearInterval(timerRef.current), []);
return {counting, remaining, start, stop};
}
倒計時按鈕看似簡單,實則涉及狀態管理、非同步協調、持久化恢復、無障礙、框架整合等多維考量。封裝為可複用 Class/Hook/Component,配合 TypeScript 型別定義,能大幅提升開發效率與代碼質量,確保用戶體驗一致性。