当前位置:首页 > JavaScript

js 轮询实现

2026-04-07 01:41:12JavaScript

轮询的基本概念

轮询(Polling)是一种客户端定期向服务器发送请求以获取最新数据的机制。适用于实时性要求不高的场景,如检查状态更新、数据同步等。

简单定时轮询

通过 setInterval 定时发送请求,代码示例:

js 轮询实现

function pollServer() {
  fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => console.log('更新数据:', data))
    .catch(error => console.error('请求失败:', error));
}

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

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

带退避策略的轮询

当服务器压力大或网络不稳定时,可动态调整轮询间隔:

js 轮询实现

let retryCount = 0;
const maxRetry = 5;
const baseDelay = 1000;

function pollWithBackoff() {
  fetch('https://api.example.com/data')
    .then(response => {
      if (!response.ok) throw new Error('状态异常');
      retryCount = 0; // 成功时重置重试计数
      return response.json();
    })
    .then(data => {
      console.log('数据更新:', data);
      setTimeout(pollWithBackoff, baseDelay); // 正常延迟
    })
    .catch(error => {
      retryCount++;
      if (retryCount >= maxRetry) {
        console.error('达到最大重试次数');
        return;
      }
      const delay = baseDelay * Math.pow(2, retryCount); // 指数退避
      console.warn(`请求失败,${delay}ms后重试...`);
      setTimeout(pollWithBackoff, delay);
    });
}

pollWithBackoff();

长轮询(Long Polling)

服务器在有数据时才响应,减少无效请求:

function longPoll() {
  fetch('https://api.example.com/long-poll')
    .then(response => {
      if (response.status === 204) {
        // 无数据时立即重试
        longPoll();
      } else {
        return response.json().then(data => {
          console.log('收到数据:', data);
          longPoll(); // 处理完成后继续下一次轮询
        });
      }
    })
    .catch(error => {
      console.error('长轮询错误:', error);
      setTimeout(longPoll, 5000); // 错误时延迟重试
    });
}

longPoll();

终止轮询的条件

通过标志位或外部事件停止轮询:

let isPollingActive = true;

function conditionalPoll() {
  if (!isPollingActive) return;

  fetch('https://api.example.com/conditional')
    .then(response => response.json())
    .then(data => {
      console.log('当前数据:', data);
      if (data.status === 'COMPLETED') {
        isPollingActive = false; // 满足条件时停止
      } else {
        setTimeout(conditionalPoll, 3000);
      }
    });
}

conditionalPoll();

// 通过按钮点击停止
document.getElementById('stopButton').addEventListener('click', () => {
  isPollingActive = false;
});

注意事项

  • 性能影响:高频轮询会增加服务器负载,需合理设置间隔时间。
  • 错误处理:网络波动或服务异常时需实现重试机制。
  • 替代方案:对于高实时性需求,建议考虑 WebSocket 或 Server-Sent Events(SSE)。

标签: js
分享给朋友:

相关文章

js实现百叶窗

js实现百叶窗

使用CSS和JavaScript实现百叶窗效果 通过CSS动画和JavaScript事件监听可以实现百叶窗效果。核心思路是将内容区域分割为多个条状元素,通过控制它们的展开/折叠状态来模拟百叶窗。 &…

js实现驼峰

js实现驼峰

实现驼峰命名的几种方法 使用正则表达式和字符串替换 通过正则表达式匹配字符串中的特定模式(如下划线或短横线),并将其后的字母转换为大写,同时移除分隔符。 function toCamelCase(s…

js实现vue路由

js实现vue路由

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

js实现路由

js实现路由

js实现路由的方法 在JavaScript中实现路由功能可以通过多种方式完成,以下是几种常见的方法: 使用原生JavaScript实现路由 通过监听window.onhashchange事件来实现基…

js 实现滚动

js 实现滚动

实现滚动的方法 使用 window.scrollTo() window.scrollTo() 方法可以滚动到文档中的特定位置。可以指定 x 和 y 坐标,或者使用平滑滚动的选项。 // 滚动到指定位…

js实现搜索

js实现搜索

实现搜索功能的方法 在JavaScript中实现搜索功能可以通过多种方式完成,以下是几种常见的实现方法。 使用数组的filter方法 通过数组的filter方法可以筛选出符合条件的数据项。假设有一个…