setInterval导致错误的函数结果

时间:2015-04-26 13:04:46

标签: javascript

当我在setIntervals中运行倒计时函数时,它每秒返回相同的输出,但是我传递给函数的值会发生变化。这是jsFiddle

var date = new Date(2017, 3, 27, 21).getTime();
function countdown(milliseconds) {
    console.log(milliseconds);
    var CDDate = {
        seconds: 0,
        minutes: 0,
        hours: 0,
        days: 0
    }
    x = milliseconds / 1000;
    CDDate.seconds = Math.round(x % 60);
    x /= 60;
    CDDate.minutes = Math.round(x % 60);
    x /= 60;
    CDDate.hours = Math.round(x % 25);
    x /= 24;
    CDDate.days = Math.floor(x);
    return CDDate;
}

var diff = date - Date.now();
setInterval(function(){
    console.log(countdown(--diff));
},1000)

1 个答案:

答案 0 :(得分:0)

以下是工作示例代码:

var date = new Date(2017, 3, 27, 21).getTime();
function countdown(milliseconds) {
    var CDDate = {
        seconds: 0,
        minutes: 0,
        hours: 0,
        days: 0
    }
    x = milliseconds;
    CDDate.seconds = Math.round((x+30) % 60);
    x = (x/60);
    CDDate.minutes = Math.round(x % 60);
    x = x/60;
    CDDate.hours = Math.round(x % 24);
    x = x/24;
    CDDate.days = Math.floor(x);
    return CDDate;
}
var diff = date - Date.now();
diff = diff/1000;
setInterval(function(){
    var returnVal = countdown(--diff);
    document.getElementById('low').innerHTML = returnVal.seconds;
    document.getElementById('min').innerHTML = returnVal.minutes;
    document.getElementById('hrs').innerHTML = returnVal.hours;
    document.getElementById('day').innerHTML = returnVal.days;
},1000)
Seconds: <div id="low"></div>
Minuts: <div id="min"></div>
Hours: <div id="hrs"></div>
Days: <div id="day"></div>
<div id="mil"></div>

您将毫秒计数为秒,而在setInterval函数中,您已经过了1秒。是时候召回这个职能了。

我在差异计算后添加了这一行:diff = diff/1000;并将其转换为秒。现在工作正常。