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

网页动态显示API调用后已过时间的实现及计时问题解决

解决方案:修复动态刷新时间显示问题

核心思路

要解决你的两个问题,关键在于持久化存储API最后刷新的时间戳,同时严格控制计时范围在0-5分钟内,到点自动重置并触发API调用。

前端代码修改(index.html)

<!DOCTYPE html>
<html>
<head>
    <title>Refreshed Time Demo</title>
    <script>
        let timerInterval;
        const REFRESH_INTERVAL = 5 * 60 * 1000; // 5分钟对应的毫秒数

        // 初始化:从本地存储读取最后刷新时间,无则初始化并调用API
        function initLastRefreshedTime() {
            let lastRefreshed = localStorage.getItem('lastRefreshed');
            if (!lastRefreshed) {
                lastRefreshed = Date.now().toString();
                localStorage.setItem('lastRefreshed', lastRefreshed);
                callAPI();
            }
            updateDisplay(parseInt(lastRefreshed));
            startTimer(parseInt(lastRefreshed));
        }

        // 更新页面显示文本
        function updateDisplay(lastRefreshedTime) {
            const now = Date.now();
            const diff = now - lastRefreshedTime;
            const seconds = Math.floor(diff / 1000);
            const minutes = Math.floor(seconds / 60);

            let displayText;
            if (seconds < 60) {
                displayText = `Last Refreshed ${seconds} sec ago`;
            } else if (minutes < 5) {
                displayText = `Last Refreshed ${minutes} min ago`;
            } else {
                // 超过5分钟直接重置并调用API
                resetTimerAndCallAPI();
                return;
            }
            document.getElementById('refreshed-time').textContent = displayText;
        }

        // 启动计时更新
        function startTimer(lastRefreshedTime) {
            clearInterval(timerInterval);
            timerInterval = setInterval(() => {
                updateDisplay(lastRefreshedTime);
            }, 1000); // 每秒更新一次显示
        }

        // 重置计时并触发API调用
        function resetTimerAndCallAPI() {
            clearInterval(timerInterval);
            const newTime = Date.now();
            localStorage.setItem('lastRefreshed', newTime.toString());
            callAPI();
            startTimer(newTime);
        }

        // API调用逻辑
        function callAPI() {
            fetch('/api/trends')
                .then(response => response.json())
                .then(data => {
                    // 处理API返回的数据,比如更新页面内容
                    console.log('API数据已刷新:', data);
                })
                .catch(error => console.error('API调用失败:', error));
        }

        // 页面加载时初始化
        window.onload = initLastRefreshedTime;

        // 全局定时任务做双重保障,避免前端计时器异常
        setInterval(() => {
            resetTimerAndCallAPI();
        }, REFRESH_INTERVAL);
    </script>
</head>
<body>
    <div id="refreshed-time"></div>
</body>
</html>

后端代码优化建议(server.js)

可以在API响应中返回后端的刷新时间戳,避免本地时间被篡改,前端优先使用该值:

// server.js 示例片段
app.get('/api/trends', (req, res) => {
    const currentTime = Date.now();
    // 模拟获取趋势数据
    const trends = ['#Trend1', '#Trend2', '#Trend3'];
    res.json({
        data: trends,
        lastRefreshed: currentTime // 返回后端记录的刷新时间
    });
});

前端对应的callAPI函数修改为:

function callAPI() {
    fetch('/api/trends')
        .then(response => response.json())
        .then(data => {
            console.log('API数据已刷新:', data);
            // 用后端返回的时间更新本地存储
            localStorage.setItem('lastRefreshed', data.lastRefreshed.toString());
            startTimer(data.lastRefreshed);
        })
        .catch(error => console.error('API调用失败:', error));
}

关键修复点

  • 解决浏览器刷新后计时重置:用localStorage持久化存储最后刷新的时间戳,页面加载时读取该值而非从0开始计时。
  • 解决超过5分钟仍计时:每次更新显示时计算时间差,若超过5分钟则直接重置计时器并调用API;同时保留全局5分钟定时任务作为双重保障,避免前端计时器异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 08:36:05