递归倒数计时器

时间:2016-05-10 22:59:55

标签: javascript recursion timer countdown

我正在尝试创建一个从25分钟开始并以0结束的javascript计数器。想法是将分钟/秒显示为页面上的倒计时时钟(我的目标div称为'txt')。但是我没有得到我想要的结果 - 每次运行函数时,计时器都不会减去(每隔ms)。关于我哪里出错的任何想法?代码如下:

function countdown() {

    var target = 1500000; // 25 mins
    var current = 1000; // 0 secs

    for (var i=0; i<5; i++) {
        var diff = target-current;           // calculates the 25 minutes
        var min = Math.floor(diff/1000/60);  //gets mins
        var sec = (diff/1000) % 60;          // gets secs
        current = current+1000;

        document.getElementById("txt").innerHTML = min + ":" + sec;
        var t = setTimeout(countdown, 2500);}
    }

}

2 个答案:

答案 0 :(得分:1)

您需要定义函数外部的当前值。目前,每次运行该功能时,您都将其重置为1000。

答案 1 :(得分:0)

你去:

var target = 1500000; // 25 mins
var current = 0; // 0 secs
function countdown() {
    current += 1000;
    var diff = target-current;           // calculates the 25 minutes
    var min = Math.floor(diff/1000/60);  //gets mins
    var sec = (diff/1000) % 60;          // gets secs

    document.getElementById("txt").innerHTML = min + ":" + sec;
    if (diff > 0)
        setTimeout(countdown, 1000);

}

countdown();

JSFiddle运行示例:https://jsfiddle.net/epcmw0uc/5/