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

如何制作页面刷新即重置、从加载起计时的HTML+JS倒计时器?

纯HTML+JS实现刷新重置的页面加载倒计时器

直接上可运行的代码,完全满足你的需求:

<!DOCTYPE html>
<html>
<head>
    <title>页面加载倒计时器</title>
    <style>
        #countdown {
            font-size: 2rem;
            font-weight: bold;
            margin: 2rem;
        }
    </style>
</head>
<body>
    <div id="countdown"></div>

    <script>
        // 自定义倒计时时长(单位:小时)
        const COUNTDOWN_HOURS = 1; // 可修改为你需要的小时数

        // 页面加载时计算结束时间:当前时间 + 指定小时数的毫秒数
        const endTime = new Date().getTime() + COUNTDOWN_HOURS * 3600 * 1000;

        // 更新倒计时显示的函数
        function updateCountdown() {
            const now = new Date().getTime();
            const remainingTime = endTime - now;

            // 计算剩余的时、分、秒
            const hours = Math.floor((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);

            // 格式化数字,确保两位数显示
            const formattedHours = String(hours).padStart(2, '0');
            const formattedMinutes = String(minutes).padStart(2, '0');
            const formattedSeconds = String(seconds).padStart(2, '0');

            const countdownElement = document.getElementById('countdown');
            
            if (remainingTime > 0) {
                countdownElement.textContent = `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
            } else {
                countdownElement.textContent = '倒计时结束!';
                // 倒计时结束后清除定时器,避免性能浪费
                clearInterval(countdownInterval);
            }
        }

        // 初始化显示一次,避免首次加载延迟
        updateCountdown();
        // 每秒更新一次倒计时
        const countdownInterval = setInterval(updateCountdown, 1000);
    </script>
</body>
</html>

核心逻辑说明

  • 刷新自动重置:每次页面加载时,endTime都会基于当前时刻重新计算,不依赖本地存储或外部时间源,刷新后直接从指定小时数重新开始计时。
  • 基于页面加载时刻计时:起始时间取页面加载时的时间戳(new Date().getTime()),加上你设置的小时数对应的毫秒数,精准从加载时刻开始倒计时。
  • 灵活调整时长:修改COUNTDOWN_HOURS的值即可自定义倒计时小时数,比如设为2就是2小时倒计时。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:15:55