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

Ajax返回分秒格式时间如何实现1秒精度逐秒递减倒计时

实现方案

直接修改原AJAX回调逻辑即可,完整可运行代码如下:

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var valr5 = this.responseText;
        // 将返回的「分.秒」格式字符串转换为总秒数计算
        const timeParts = valr5.split('.');
        let totalSeconds = parseInt(timeParts[0]) * 60 + parseInt(timeParts[1]);
        const countdownDom = document.getElementById("countdown");

        // 时间格式化工具:总秒数转 MM:SS 格式,自动补前导零
        const formatCountdown = (sec) => {
            const minutes = Math.floor(sec / 60).toString().padStart(2, '0');
            const seconds = (sec % 60).toString().padStart(2, '0');
            return `${minutes}:${seconds}`
        }

        // 首次渲染初始时间
        countdownDom.innerHTML = formatCountdown(totalSeconds);

        // 初始时间已为0直接跳转
        if (totalSeconds <= 0) {
            window.location = "index.php";
            return;
        }

        // 启动1秒间隔定时器
        const timer = setInterval(() => {
            totalSeconds--;
            countdownDom.innerHTML = formatCountdown(totalSeconds);
            // 计时归零处理
            if (totalSeconds <= 0) {
                clearInterval(timer);
                window.location = "index.php";
            }
        }, 1000)
    }
};

逻辑说明

  • 把后端返回的时间格式统一转换为总秒数计算,避免逐次处理字符串带来的逻辑冗余
  • 用padStart方法自动给不足两位的分钟、秒数补前导零,保证显示格式统一为MM:SS
  • 定时器每1秒执行一次,计时结束后先清除定时器避免内存泄漏,再执行页面跳转
  • 额外兼容了初始返回时间已经是0的边界场景,避免无效定时器运行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 11:27:03