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

如何用JavaScript实现内容显示一小时后自动消失的功能

解决方案

1. 单用户场景实现

如果仅需要当前点击的用户自己看到内容一小时,先修正你代码里的异步逻辑错误和setTimeout用法,同时需要把内容插入到页面DOM中:

// 先在页面中添加一个显示内容的容器:<div id="contentContainer"></div>
function fetchAndShowForHour() {
  const url = "https://example.com";
  const contentContainer = document.getElementById('contentContainer');
  
  const xhr = new XMLHttpRequest();
  xhr.open("GET", url);

  xhr.onreadystatechange = function () {
    // 确保请求成功完成
    if (xhr.readyState === 4 && xhr.status === 200) {
      // 将获取到的内容显示在容器中
      contentContainer.textContent = xhr.responseText;
      contentContainer.style.display = 'block';
      
      // 一小时后隐藏内容(3600000毫秒 = 1小时)
      setTimeout(() => {
        contentContainer.style.display = 'none';
      }, 3600000);
    }
  };

  xhr.send();
}

2. 多用户全局可见实现

如果要让所有访问网站的用户都能看到点击后更新的内容一小时,仅靠前端无法实现,必须配合后端:

  • 后端需要维护两个状态:当前要展示的JSON内容、内容的过期时间(可存在数据库或缓存中)
  • 点击按钮时,前端调用后端接口:
    1. 后端从目标URL拉取JSON内容
    2. 后端记录该内容,并设置过期时间为「当前时间 + 3600秒」
  • 前端页面加载/定时刷新时,请求后端接口:
    1. 后端判断当前时间是否在过期时间范围内
    2. 未过期则返回内容,已过期则返回空或提示
    3. 前端根据返回结果控制内容的显示/隐藏

前端示例代码(配合后端接口):

// 点击按钮触发全局内容更新
function triggerGlobalContent() {
  fetch('/api/update-global-content', { method: 'POST' })
    .then(res => res.json())
    .then(data => {
      if (data.success) {
        const container = document.getElementById('contentContainer');
        container.textContent = data.content;
        container.style.display = 'block';
      }
    });
}

// 页面加载时获取当前是否有可显示的内容
function loadGlobalContent() {
  fetch('/api/get-global-content')
    .then(res => res.json())
    .then(data => {
      const container = document.getElementById('contentContainer');
      if (data.isValid) {
        container.textContent = data.content;
        container.style.display = 'block';
        
        // 计算剩余显示时间,设置定时器自动隐藏
        const remainingTime = data.expireTime - Date.now();
        if (remainingTime > 0) {
          setTimeout(() => {
            container.style.display = 'none';
          }, remainingTime);
        }
      } else {
        container.style.display = 'none';
      }
    });
}

// 页面加载完成后自动执行
window.onload = loadGlobalContent;

关键问题说明

  • 原代码中xhr.send()后直接取xhr.responseText是错误的,XHR是异步操作,必须在onreadystatechange回调内处理响应
  • setTimeout(Text, 1000)用法错误,setTimeout第一个参数必须是函数,不能直接传字符串内容
  • 多用户同步显示的核心是后端统一维护内容和过期时间,否则每个用户的前端状态独立,无法实现全局同步

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:40:25