用戶註冊頁面,按鈕初始不可用,倒計時 10 秒後自動啟用,按鈕文字實時顯示剩餘秒數,提升用戶閱讀協議的引導效果。
var MyCount = 10;
var intervalID;
function CountDown() {
var btnReg = document.getElementById("btnReg");
if (!btnReg) return; // 防御:按鈕未渲染完成
if (MyCount <= 0) {
btnReg.disabled = false; // 啟用按鈕
btnReg.value = "同意"; // 修改文字
clearInterval(intervalID); // 清除定時器
} else {
btnReg.value = "請仔細閱讀協議(還剩" + MyCount + "秒)";
MyCount--;
}
}
intervalID = setInterval(CountDown, 1000);
if (btnReg) 防止網速慢時定時器先於 DOM 就緒觸發報錯。disabled = false 啟用,disabled = "disabled" 或 true 禁用均可。clearInterval,避免內存洩漏與邏輯錯誤。MyCount、intervalID 掛載於 window,簡單場景可接受,複雜應用建議封裝閉包或類。<textarea>請同意本站的協議</textarea><br />
<input id="btnReg" type="button" value="同意" disabled="disabled" />
const start = performance.now();
const duration = 10000;
function tick(now) {
const remain = Math.ceil((duration - (now - start)) / 1000);
if (remain <= 0) { enableBtn(); return; }
btn.value = `請仔細閱讀協議(還剩${remain}秒)`;
requestAnimationFrame(tick);
}
requestAnimationFrame(tick);
class CountdownButton {
constructor(btnId, seconds, finalText = "同意") {
this.btn = document.getElementById(btnId);
this.seconds = seconds;
this.finalText = finalText;
this.timer = null;
}
start() {
this.btn.disabled = true;
this.tick();
}
tick() {
if (this.seconds <= 0) {
this.btn.disabled = false;
this.btn.value = this.finalText;
return;
}
this.btn.value = `請仔細閱讀協議(還剩${this.seconds}秒)`;
this.seconds--;
this.timer = setTimeout(() => this.tick(), 1000);
}
stop() { clearTimeout(this.timer); }
}
// 使用
new CountdownButton('btnReg', 10).start();
避免用戶未看到協議區域就開始倒計時。