JavaScript倒计时器未启动

时间:2011-07-25 02:59:02

标签: javascript

我尝试在我的页面上使用此JavaScript倒计时器,但计时器将无法启动。 我做错了什么?

var CountdownID = null;
var start_msecond = 9;
var start_sec = 120;

window.onload = countDown(start_msecond, start_sec, "timerID");

function countDown(pmsecond, psecond, timerID) {
var msecond = ((pmsecond < 1) ? "" : "") + pmsecond;
var second = ((psecond < 9) ? "0": "") + psecond;

document.getElementById(timerID).innerHTML = second + "." + msecond;

if (pmsecond == 0 && (psecond-1) < 0) { //Recurse timer
    clearTimeout(CountdownID);

    var command = "countDown("+start_msecond+", "+start_sec+", '"+timerID+"')";
    CountdownID = window.setTimeout(command, 100);

    alert("Time is Up! Enter your PIN now to subscribe!");
}
else { //Decrease time by one second
    --pmsecond;
    if (pmsecond == 0) {
        pmsecond=start_msecond;
           --psecond;
    }
    if (psecond == 0) {
        psecond=start_sec;
    }
    var command = "countDown("+pmsecond+", "+psecond+", '"+timerID+"')";
    CountdownID = window.setTimeout(command, 100);
}
}

<span style="color:red" name="timerID" id="timerID">91.6</span>

2 个答案:

答案 0 :(得分:2)

这是您首先需要做的事情

window.onload = countDown(start_msecond, start_sec, "timerID");

应该是

window.onload = function () {
   countDown(start_msecond, start_sec, "timerID");
}

你也应该避免在setTimeout函数中使用字符串:

CountdownID = window.setTimeout(function () {
   countDown(pmsecond,psecond,"timerID");
}, 100);

答案 1 :(得分:0)