当前位置:首页 > JavaScript

js 实现轮询

2026-01-31 18:10:37JavaScript

轮询的基本概念

轮询是一种客户端定期向服务器发送请求以获取最新数据的技术,适用于需要实时更新但无法使用WebSocket或Server-Sent Events(SSE)的场景。

js 实现轮询

简单轮询实现

通过 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);

指数退避轮询

当服务器压力大时,可采用指数退避策略动态调整轮询间隔:

let retryCount = 0;
const maxRetries = 5;
const baseDelay = 1000; // 初始延迟1秒

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 > maxRetries) {
        console.error('达到最大重试次数');
        return;
      }
      const delay = baseDelay * Math.pow(2, retryCount);
      console.log(`第${retryCount}次重试,延迟${delay}ms`);
      setTimeout(pollWithBackoff, delay);
    });
}

pollWithBackoff();

基于Promise的轮询

结合 async/await 实现更可控的轮询逻辑:

async function pollUntilCondition(conditionFn, interval = 3000) {
  while (true) {
    try {
      const response = await fetch('https://api.example.com/status');
      const data = await response.json();
      if (conditionFn(data)) {
        console.log('条件满足:', data);
        return data;
      }
      await new Promise(resolve => setTimeout(resolve, interval));
    } catch (error) {
      console.error('轮询异常:', error);
      await new Promise(resolve => setTimeout(resolve, interval));
    }
  }
}

// 使用示例:检测任务是否完成
pollUntilCondition(data => data.status === 'completed');

注意事项

  • 性能优化:避免高频轮询,根据业务需求合理设置间隔时间。
  • 错误处理:添加网络异常和服务器错误的重试机制。
  • 资源释放:在页面卸载时清除轮询(如 beforeunload 事件中调用 clearInterval)。

标签: js
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 或直接使用 window.location 实现页面跳转,适用于普通跳转或带参数的 URL。 // 方…

css3结合js制作

css3结合js制作

CSS3 结合 JavaScript 制作动态效果 CSS3 和 JavaScript 结合可以实现丰富的动态效果,包括动画、交互和响应式设计。以下是几种常见的实现方式: CSS3 动画与 Jav…

js实现继承

js实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Paren…

js 实现vue

js 实现vue

Vue.js 的基本实现 在 JavaScript 中实现 Vue.js 的核心功能,可以通过数据绑定、响应式系统和虚拟 DOM 来实现。以下是实现 Vue.js 核心功能的简化版本。 数据响应式…

js实现类

js实现类

JavaScript 实现类的几种方式 JavaScript 是一种基于原型的语言,但在 ES6 之后引入了 class 语法糖,使得实现类更加直观。以下是几种常见的实现方式: 使用构造函数 传统…

js实现抽奖

js实现抽奖

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