You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用setInterval每秒调用JavaScript倒计时函数失效问题

解决你的JavaScript倒计时setInterval不更新问题

嘿,我一眼就看到问题所在了——你的倒计时之所以不动,不是setInterval没工作,而是你获取当前时间的方式错了!

你把var today = new Date();写在了全局作用域里,这意味着这个变量只会在页面加载的时候被赋值一次,之后每次调用getTimeDifference,用的都是同一个旧的时间值。哪怕setInterval每秒都跑runCountdown,计算出来的时间差也不会变,页面显示当然就卡住啦。

修正后的代码

把获取当前时间的逻辑移到getTimeDifference函数内部,这样每次计算时间差时,都会拿到实时的当前时间:

// 设置结束日期和时间
const endTimeDate = "2022-01-12 21:52";

// 计算日期时间差
function getTimeDifference(endtime) {
    // 每次计算都获取实时的当前时间
    const today = new Date();
    const total = Date.parse(endtime) - Date.parse(today);
    
    // 处理倒计时结束的情况
    if (total <= 0) {
        return { total: 0, days: 0, hours: 0, minutes: 0, seconds: 0 };
    }

    const seconds = Math.floor((total / 1000) % 60);
    const minutes = Math.floor((total / 1000 / 60) % 60);
    const hours = Math.floor((total / 1000 / 60 / 60) % 24);
    const days = Math.floor(total / 1000 / 60 / 60 / 24);
    
    return { total, days, hours, minutes, seconds };
}

function runCountdown() {
    const t = getTimeDifference(endTimeDate);
    document.getElementById('days').textContent = `${t.days} D`;
    document.getElementById('hours').textContent = `${t.hours} H`;
    document.getElementById('minutes').textContent = `${t.minutes} M`;
    document.getElementById('seconds').textContent = `${t.seconds} S`;
    
    // 如果倒计时结束,清除定时器
    if (t.total <= 0) {
        clearInterval(countdownInterval);
    }
}

// 保存定时器ID,方便后续清除
const countdownInterval = window.setInterval(runCountdown, 1000);

额外优化建议

  • 数字补零:比如当秒数小于10时,显示05而不是5,可以加个小函数处理:
    function padZero(num) {
        return num < 10 ? `0${num}` : num;
    }
    
    之后用padZero(t.seconds)这样的写法,倒计时会更美观。
  • 用textContent替代innerHTML:如果只是插入纯文本,textContent比innerHTML更安全,性能也更好。
  • 及时清除定时器:当倒计时结束后,清除定时器避免不必要的性能消耗。

内容的提问来源于stack exchange,提问作者Communicator_XoX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 02:52:42