按鈕初始狀態為「禁用」,倒數 10 秒後自動啟用並顯示「確定」;倒數過程中按鈕文字即時顯示剩餘秒數(如「確(9)定」)。
<head>
<script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script>
var count = 10;
var timerId;
function startCountdown() {
$('#btnSubmit').prop('disabled', true).val('確(' + count + ')定');
timerId = setTimeout(tick, 1000);
}
function tick() {
count--;
if (count > 0) {
$('#btnSubmit').val('確(' + count + ')定');
timerId = setTimeout(tick, 1000);
} else {
$('#btnSubmit').prop('disabled', false).val('確定');
clearTimeout(timerId);
}
}
$(function() { startCountdown(); });
</script>
</head>
<body>
<button id="btnSubmit" disabled>確定</button>
</body>
setTimeout 單次觸發,但在回呼函式 tick 內再次呼叫自己,形成類似 setInterval 的週期效果,但可精確控制終止條件。count 追蹤剩餘秒數,timerId 保存定時器 ID 供 clearTimeout 取消。.prop('disabled', true/false) 切換禁用狀態;.val() 更新按鈕文字。clearTimeout(timerId) 再啟動新計時。setInterval 無法在回呼中動態決定是否繼續,且若回呼執行時間超過間隔會產生堆疊問題;遞迴 setTimeout 更彈性。let/const、箭頭函式、async/await + Promise 封裝成可複用的 countdownBtn(selector, seconds) 元件。function countdownButton($btn, seconds, finalText) {
var remaining = seconds;
$btn.prop('disabled', true);
function update() {
$btn.val(finalText.replace('{n}', remaining));
if (remaining-- > 0) setTimeout(update, 1000);
else $btn.prop('disabled', false).val(finalText.replace('{n}', ''));
}
update();
}
// 使用
countdownButton($('#btnSubmit'), 10, '確({n})定');