为什么innerHTML在setTimeout中不起作用?

时间:2013-07-17 23:54:15

标签: javascript jquery settimeout

$(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中不起作用?倒数更好的原因是什么?  谢谢!

3 个答案:

答案 0 :(得分:3)

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

试试这个

答案 1 :(得分:2)

您还可以使其递归,以便您轻松更改要倒数的数字:

ONLINE DEMO

$(document).ready(function () {

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

    countDown(3);
});

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

ONLINE DEMO EXT.

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

答案 2 :(得分:0)

下面:

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

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