You need to enable JavaScript to run this app. jQuery实现的倒计时功能异常,固定显示1d 0h 0m 0s问题求助
优惠活动
大模型
产品
解决方案
定价
更多

jQuery实现的倒计时功能异常,固定显示1d 0h 0m 0s问题求助

问题排查与解决方案

问题原因

  • 核心错误:倒计时起始时间被写死为固定值2021-08-03,定时器每秒执行时,结束时间和起始时间的差值是固定常量,永远等于86400000毫秒(24小时),所以计算出来的天时分秒永远固定为1d 0h 0m 0s不会变化。
  • 冗余问题:同一逻辑内两次给#countdown节点赋值HTML内容,无意义且浪费性能,同时存在多余的尾随分号。

修复方案

把定时器内部的固定起始时间替换为当前实时时间,删除冗余的重复赋值操作即可。

修正后代码

let countdown = "";
// 倒计时结束时间可按需修改
const closingdate = "2021-08-04";
const countDownDate = new Date(closingdate).getTime();
const x = setInterval(function() {
    // 取当前实时时间作为倒计时起始时间
    const nowTime = new Date().getTime();
    // 计算结束时间和当前时间的差值
    const distance = countDownDate - nowTime;

    const days = Math.floor(distance / (1000 * 60 * 60 * 24));
    const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((distance % (1000 * 60)) / 1000);

    $('#countdown').html(days + "d " + hours + "h " + minutes + "m " + seconds + "s ");
    countdown = $('#countdown').html();

    if (distance < 0) {
        clearInterval(x);
        document.getElementById("countdown").innerHTML = "Closed";
    }
}, 1000);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 15:24:03