3

我有这个 javascript 代码

 function updateClock() {
        time = time + 1;
       var  mins = 1;
       var secs = 50
       var mins = parseInt(mins/ 60);
       var secs = time - mins * 60;

        mins = mins.toString();
        secs = secs.toString();

        if (mins.length < 2)
            mins = "0" + mins;
        if (secs.length < 2)
            secs = "0" + secs;


        var timeDisp = document.getElementById("timerDisp");
        timeDisp.innerText = mins + ":" + secs;
    }

它在计算已经过去了多少时间,但是如果我想倒计时怎么办?(或相反)而不是跟踪时间,我想给出一个确定的时间,然后随着时间的推移,时间减少,比如说 1 分 15 秒,我将如何在给定的代码上执行它?

4

2 回答 2

5

您可以updateClock()每 1 秒执行一次setTimeout()以创建倒计时。

var time;
function UpdateClock() {
    time = time - 1;

    if (time > 0) {
        setTimeout(UpdateClock, 1000); // 1000 miliseconds
    }

    var mins = parseInt(time / 60, 10);
    var secs = time - mins * 60;

    mins = mins.toString();
    secs = secs.toString();

    if (mins.length < 2)
        mins = "0" + mins;
    if (secs.length < 2)
        secs = "0" + secs;

    timeDisp.innerText = mins + ":" + secs + " left";
}

function StartCountdown(countdowntime) {
    time = countdowntime;
    updateClock();
}
于 2012-10-04T07:22:57.843 回答
0

您可以使用 setInterval() 进行倒计时。请参阅http://www.w3schools.com/jsref/met_win_setinterval.asp

于 2012-10-04T07:30:48.810 回答