setTimeout("var t = 60; if(t>1) { this.btn_captcha = t + ['秒後重新獲取']; t = t - 1; } else { this.btn_captcha = ['獲取短信驗證碼']; }", 1000);
var t = 60;
var btn = document.getElementById('captchaBtn'); // 獲取按鈕 DOM
btn.disabled = true;
var timer = setInterval(function() {
t--;
if (t <= 0) {
btn.innerText = '獲取短信驗證碼';
btn.disabled = false;
clearInterval(timer); // 必須清理定時器
} else {
btn.innerText = t + '秒後重新獲取';
}
}, 1000);
data() {
return { countdown: 0, timer: null };
},
methods: {
startCountdown() {
this.countdown = 60;
this.timer = setInterval(() => {
this.countdown--;
if (this.countdown <= 0) {
clearInterval(this.timer);
this.timer = null;
}
}, 1000);
}
},
beforeDestroy() {
if (this.timer) clearInterval(this.timer);
}
const countdown = ref(0);
let timer = null;
const startCountdown = () => {
countdown.value = 60;
timer = setInterval(() => {
countdown.value--;
if (countdown.value <= 0) clearInterval(timer);
}, 1000);
};
onUnmounted(() => timer && clearInterval(timer));
| API | 用途 | 返回值 |
|---|---|---|
| setTimeout(fn, ms) | 延遲執行一次 | timerId (可 clearTimeout) |
| setInterval(fn, ms) | 循環執行 | timerId (可 clearInterval) |
原代碼混淆了 `setTimeout`/`setInterval` 用法、字符串/函數參數、作用域綁定。正確模式:`setInterval` + 狀態變量 + 組件生命周期清理。