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

如何用LocalStorage保存倒计时进度条进度(页面刷新后)

解决页面刷新后倒计时进度丢失的问题

我使用了带进度条的倒计时功能,但现有代码无法实现页面刷新后保存进度的效果,请问该如何解决?

原代码如下:

<div id="progressBar">
    <div class="bar"></div>
</div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
    var seconds = {$timer_limited->sec}; // 10000
    $(document).ready(function () {
        function progress(timeleft, timetotal, $element) {
            
            var progressBarWidth = timeleft * $element.width() / timetotal;
           
            $element.find('div').animate({ width: progressBarWidth }, 500);
            if(timeleft > 0) {
                setTimeout(function() {
                    progress(timeleft - 1, timetotal, $element);
                }, 1000);
            }
        };

        progress(seconds, seconds, $('#progressBar'));
    });
</script>
<style>
    #progressBar {
        width: 100%;
        height: 4px;
        background-color: #DDDFE2;
    }
    #progressBar div {
        height: 100%;
        line-height: 22px;
        width: 0;
        background-color: #D03637;
    }
</style>

解决方案:利用localStorage存储倒计时关键时间点

页面刷新后内存变量会被清空,所以需要把倒计时的核心时间数据存在本地存储(localStorage)里,刷新后通过存储的数据恢复进度。以下是修改后的代码:

<div id="progressBar">
    <div class="bar"></div>
</div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
    // 初始总时长(秒)
    const totalSeconds = {$timer_limited->sec}; // 示例值:10000
    const STORAGE_KEY = 'countdown_end_time'; // 本地存储的键名

    $(document).ready(function () {
        // 获取当前剩余时间
        function getRemainingTime() {
            const endTimeStr = localStorage.getItem(STORAGE_KEY);
            if (!endTimeStr) return totalSeconds;
            
            const endTime = parseInt(endTimeStr);
            const now = Date.now();
            // 计算剩余秒数,取整且不小于0
            const remaining = Math.max(0, Math.floor((endTime - now) / 1000));
            
            // 倒计时已结束,清除存储记录
            if (remaining === 0) {
                localStorage.removeItem(STORAGE_KEY);
            }
            return remaining;
        }

        function initCountdown() {
            let remainingTime = getRemainingTime();
            // 首次加载时,设置倒计时结束时间戳
            if (remainingTime === totalSeconds) {
                const endTime = Date.now() + totalSeconds * 1000;
                localStorage.setItem(STORAGE_KEY, endTime.toString());
            }

            function progress(timeleft, timetotal, $element) {
                const progressBarWidth = timeleft * $element.width() / timetotal;
                // 用CSS直接设置宽度,配合过渡动画更平滑
                $element.find('div').css('width', progressBarWidth);

                if (timeleft > 0) {
                    setTimeout(function() {
                        progress(timeleft - 1, timetotal, $element);
                    }, 1000);
                } else {
                    // 倒计时结束,清除存储
                    localStorage.removeItem(STORAGE_KEY);
                }
            };

            progress(remainingTime, totalSeconds, $('#progressBar'));
        }

        initCountdown();
    });
</script>
<style>
    #progressBar {
        width: 100%;
        height: 4px;
        background-color: #DDDFE2;
    }
    #progressBar div {
        height: 100%;
        line-height: 22px;
        width: 0;
        background-color: #D03637;
        /* 添加过渡动画,让进度条变化更平滑 */
        transition: width 1s linear;
    }
</style>

关键说明:

  • 存储结束时间而非剩余时间:用时间戳记录倒计时的结束时刻,刷新后通过当前时间与结束时间的差值计算剩余时长,避免定时器累积误差。
  • 页面加载时恢复进度:优先读取localStorage中的结束时间,计算剩余时间后继续倒计时;如果没有存储记录,就从初始时长开始。
  • 优化动画效果:把原来的animate方法换成CSS过渡,避免多次动画调用导致的进度偏差,同时让进度条变化更流畅。
  • 自动清理存储:倒计时结束后自动清除localStorage中的记录,下次加载会重新启动倒计时。

额外注意:

  • 如果需要手动重置倒计时,可以调用localStorage.removeItem('countdown_end_time'),刷新页面后就会重新开始。
  • localStorage是域名级别的存储,同一域名下的页面共享该数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 08:00:36