当前位置:首页 > 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.href = 'https://…

js实现类

js实现类

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

js jquery

js jquery

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。它兼容多种浏览器,提供易于使用的 API,使开发者能够…

js手势实现

js手势实现

手势识别实现方法 在JavaScript中实现手势识别通常涉及监听触摸事件(touchstart、touchmove、touchend)或鼠标事件(mousedown、mousemove、mouseu…

js实现定位

js实现定位

使用Geolocation API获取当前位置 在JavaScript中,可以通过浏览器内置的Geolocation API获取用户的地理位置信息。该API需要用户授权才能访问位置数据。 if (n…

js 实现递归

js 实现递归

递归的基本概念 递归是指函数直接或间接调用自身的过程。在JavaScript中,递归通常用于解决可以分解为相似子问题的问题,如阶乘、斐波那契数列、树形结构遍历等。 递归的实现要点 基线条件(Base…