当前位置:首页 > JavaScript

js 轮询实现

2026-03-15 08:13:13JavaScript

轮询的基本概念

轮询是一种客户端定期向服务器发送请求以检查数据更新的技术。适用于实时性要求不高的场景,但可能增加服务器负担。

简单轮询实现

使用 setInterval 定时发起请求:

function pollServer() {
  fetch('/api/check-updates')
    .then(response => response.json())
    .then(data => {
      if (data.hasUpdates) {
        // 处理更新
      }
    });
}

const pollInterval = setInterval(pollServer, 5000); // 每5秒轮询

// 停止轮询
// clearInterval(pollInterval);

带退避策略的轮询

当无更新时逐步延长轮询间隔:

let retryDelay = 1000;
const maxDelay = 60000;

function smartPoll() {
  fetch('/api/check')
    .then(res => res.json())
    .then(data => {
      if (data.updated) {
        retryDelay = 1000; // 重置延迟
        // 处理数据
      } else {
        retryDelay = Math.min(retryDelay * 2, maxDelay);
      }
      setTimeout(smartPoll, retryDelay);
    });
}

smartPoll(); // 启动

错误处理增强版

添加网络错误处理和重试机制:

let retryCount = 0;
const MAX_RETRIES = 3;

function robustPoll() {
  fetch('/api/data')
    .then(response => {
      if (!response.ok) throw new Error('Server error');
      return response.json();
    })
    .then(handleData)
    .catch(error => {
      if (retryCount < MAX_RETRIES) {
        retryCount++;
        setTimeout(robustPoll, 2000 * retryCount);
      } else {
        console.error('Polling failed after retries');
      }
    });
}

function handleData(data) {
  retryCount = 0; // 成功时重置计数器
  // 业务逻辑处理
  setTimeout(robustPoll, 5000); // 正常轮询间隔
}

基于Promise的链式轮询

实现请求完成后再发起下一次请求的模式:

js 轮询实现

function chainPoll() {
  return fetch('/api/items')
    .then(res => res.json())
    .then(data => {
      // 处理数据
      return new Promise(resolve => {
        setTimeout(() => {
          resolve(chainPoll());
        }, 3000);
      });
    });
}

chainPoll(); // 启动链式调用

性能优化建议

  • 对于频繁更新的数据,考虑WebSocket替代方案
  • 添加请求取消逻辑(使用AbortController)
  • 在页面不可见时(document.visibilityState)暂停轮询
  • 服务端应设置适当的缓存控制头

标签: js
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https://…

js实现复制

js实现复制

使用document.execCommand方法 在较旧的浏览器中,可以使用document.execCommand('copy')实现复制功能。创建一个临时的textarea或input元素,将需要…

js实现复制到剪贴板

js实现复制到剪贴板

使用document.execCommand方法(传统方式,已废弃但部分浏览器仍支持) 该方法适用于旧版浏览器,但已被标记为废弃。执行前需确保文本已被选中: function copyToClipb…

js实现抽奖

js实现抽奖

实现抽奖功能的基本思路 抽奖功能的核心是随机选择奖项并展示结果。可以通过数组存储奖项,利用随机数生成索引,最后通过动画增强用户体验。 准备奖项数据 定义一个数组存储奖项信息,每个奖项可以包含名称、图…

js实现游标

js实现游标

使用JavaScript实现游标 在JavaScript中,可以通过操作DOM元素的cursor样式属性来实现自定义游标效果。以下是几种常见的实现方法: 修改默认鼠标指针样式 通过CSS的curso…

js实现vue路由

js实现vue路由

Vue 路由的基本实现 在 Vue.js 中实现路由功能通常使用 Vue Router 库。Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue R…