编程语言
首页 > 编程语言> > Javascript倒计时不起作用

Javascript倒计时不起作用

作者:互联网

我有这个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秒,我将如何在给定的代码上执行?

解决方法:

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

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

标签:winjs,javascript,dom,windows-runtime,timer
来源: https://codeday.me/bug/20190901/1785316.html