为什么 innerHTML 在 setTimeout 中不起作用

why innerHTML dosen't work inside setTimeout?

本文关键字:不起作用 setTimeout innerHTML 为什么      更新时间:2023-09-26
$(document).ready(function () {
counter.innerHTML = "3";
var t1 = setTimeout(function () { counter.innerHTML = "2"; }, 1000);
var t2 = setTimeout(function () { counter.innerHTML = "1"; }, 1000);
var t3 = setTimeout(function () { counter.innerHTML = null; }, 1000);
});

您好,为什么 innerHTML 剂量在 setTimeout 中不起作用? 有没有更好的倒计时理由? 谢谢!

$(document).ready(function () {
counter.innerHTML = "3";
var t1 = setTimeout(function () { counter.innerHTML = "2"; }, 1000);
var t2 = setTimeout(function () { counter.innerHTML = "1"; }, 2000);
var t3 = setTimeout(function () { counter.innerHTML = null; }, 3000);
});

试试这个

您还可以将其设置为递归,从而轻松更改数字以倒计时:

在线演示

$(document).ready(function () {
    function countDown(num) {
        if (num > 0) {
            counter.innerHTML = num.toString();
            setTimeout(function(){countDown(num-1)}, 1000);
        }
    }
    countDown(3);
});

您可以扩展它,以便在倒计时完成后使用回调函数:

在线演示分机

function countDown(num, callback) {
    if (num > 0) {
        counter.innerHTML = num.toString();
        setTimeout(function(){countDown(num-1, callback)}, 1000);
    } else {
        callback()
    }
}
countDown(3, function() {alert('Done!')});

在这里:

function createCountdown(count){
    counter.innerHTML = count ? count : null;
    if(count--){
        setTimeout(function(){createCountdown(count);}, 1000);
    }
}
createCountdown(3);

您的代码不起作用是因为所有setTimeout都是同时触发的。