首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

JavaScript setTimeout 語法錯誤與倒計時按鈕正確實現

     編輯:程式設計綜合問答

原代碼錯誤分析

setTimeout("var t = 60; if(t>1) { this.btn_captcha = t + ['秒後重新獲取']; t = t - 1; } else { this.btn_captcha = ['獲取短信驗證碼']; }", 1000);

錯誤原因

  1. 字符串作為第一參數:`setTimeout` 接受函數引用,傳字符串會用 `eval` 執行,不推薦且易出錯
  2. 邏輯缺陷:`setTimeout` 只執行一次,無法實現每秒更新
  3. 作用域問題:字符串中 `this` 指向 window,非組件實例
  4. 語法錯誤:`['秒後重新獲取']` 是數組,非字符串拼接

正確實現:setInterval + 閉包

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);

Vue/React 組件化寫法

Vue 2 Options API

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);
}

Vue 3 Composition API

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)
  • 優先傳遞函數引用,不傳字符串
  • 箭頭函數保持 `this` 指向
  • 組件銷毀時必須清理定時器防內存洩漏
  • 倒計時場景用 `setInterval`,非 `setTimeout` 遞歸

總結

原代碼混淆了 `setTimeout`/`setInterval` 用法、字符串/函數參數、作用域綁定。正確模式:`setInterval` + 狀態變量 + 組件生命周期清理。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved