使用 setInterval 每秒调用一个 Javascript 函数

Call a Javascript function every second with setInterval

我尝试每秒获取 JavaScript 倒计时 运行 的功能,但不知何故我无法使用 setInterval 功能。

到目前为止,JS 代码是这样的:

// Set end date and time
var enddate = new Date();
endTimeDate = "2022-01-12 21:52";

// Get date and time of today
var today = new Date();

// Calculate date and time difference
function getTimeDifference(endtime) {
    var total = Date.parse(endtime) - Date.parse(today);
    var seconds = Math.floor((total/1000) % 60);
    var minutes = Math.floor((total/1000/60) % 60);
    var hours = Math.floor((total/1000/60/60) % 24);
    var days = Math.floor(total/1000/60/60/24);

    
    return {
        total,
        days,
        hours,
        minutes,
        seconds
    };
}


function runCountdown() { 
var t = getTimeDifference(endTimeDate);

document.getElementById('days').innerHTML = t.days + " D";
document.getElementById('hours').innerHTML = t.hours + " H";
document.getElementById('minutes').innerHTML = t.minutes + " M";
document.getElementById('seconds').innerHTML = t.seconds + " S";
}

window.setInterval(runCountdown, 1000);

你的代码没有按预期工作的原因是你今天在函数之外声明,这意味着它只被调用一次,因此 diff 结果总是相同的。您可能希望将 var today = new Date(); 的赋值和声明移动到 getTimeDifference 函数中,这样 enddate 值和 today 值之间就会有实际差异。

// Set end date and time
var enddate = new Date();
endTimeDate = "2022-01-12 21:52";

// Get date and time of today

// Calculate date and time difference
function getTimeDifference(endtime) {
var today = new Date();
console.log(endtime);
    var total = Date.parse(endtime) - Date.parse(today);
    var seconds = Math.floor((total/1000) % 60);
    var minutes = Math.floor((total/1000/60) % 60);
    var hours = Math.floor((total/1000/60/60) % 24);
    var days = Math.floor(total/1000/60/60/24);

    
    return {
        total,
        days,
        hours,
        minutes,
        seconds
    };
}


function runCountdown() { 
var t = getTimeDifference(endTimeDate);

document.getElementById('days').innerHTML = t.days + " D";
document.getElementById('hours').innerHTML = t.hours + " H";
document.getElementById('minutes').innerHTML = t.minutes + " M";
document.getElementById('seconds').innerHTML = t.seconds + " S";
}

window.setInterval(runCountdown, 1000);
<div id="days">

</div>
<div id="hours">

</div>
<div id="minutes">

</div>
<div id="seconds">

</div>