当前位置:首页 > JavaScript

js轮询实现

2026-02-02 03:46:12JavaScript

轮询的基本概念

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

简单轮询实现

使用 setInterval 实现基础轮询,间隔固定时间请求数据:

function startPolling(url, interval) {
  const poll = setInterval(async () => {
    try {
      const response = await fetch(url);
      const data = await response.json();
      console.log('Received:', data);
    } catch (error) {
      console.error('Polling error:', error);
    }
  }, interval);

  // 返回停止函数
  return () => clearInterval(poll);
}

// 使用示例
const stopPolling = startPolling('/api/data', 3000);
// 需要停止时调用 stopPolling();

带退避策略的轮询

增加错误处理和动态间隔调整,避免频繁失败请求:

function startSmartPolling(url, initialInterval, maxInterval) {
  let currentInterval = initialInterval;

  const poll = async () => {
    try {
      const response = await fetch(url);
      const data = await response.json();
      console.log('Received:', data);
      currentInterval = initialInterval; // 成功时重置间隔
    } catch (error) {
      console.error('Polling error:', error);
      currentInterval = Math.min(currentInterval * 2, maxInterval); // 指数退避
    }
    setTimeout(poll, currentInterval);
  };

  poll();
  return () => clearTimeout(poll);
}

基于Promise的轮询

实现更精细的控制流程:

function promisePoll(fn, validate, interval) {
  const check = async () => {
    const result = await fn();
    if (validate(result)) {
      return result;
    }
    await new Promise(resolve => setTimeout(resolve, interval));
    return check();
  };
  return check();
}

// 使用示例
promisePoll(
  () => fetch('/api/status').then(r => r.json()),
  data => data.status === 'ready',
  1000
).then(finalData => console.log('Done:', finalData));

轮询优化建议

  • 添加请求取消逻辑(AbortController)
  • 考虑使用指数退避算法减少无效请求
  • 重要数据请求添加重试机制
  • 页面隐藏时(visibilitychange)暂停轮询

替代方案考虑

对于高实时性需求场景,建议评估以下技术:

js轮询实现

  • WebSocket 双向通信
  • Server-Sent Events (SSE) 服务器推送
  • Long Polling 长轮询技术

标签: js
分享给朋友:

相关文章

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 使用JavaScript实现拖拽功能需要监听鼠标事件,包括mousedown、mousemove和mouseup。以下是实现的基本逻辑: const draggableEleme…

js实现验证码

js实现验证码

实现验证码的JavaScript方法 生成随机验证码 使用Math.random()生成随机字符串,结合数字和字母: function generateCaptcha() { const cha…

js实现复制到剪贴板

js实现复制到剪贴板

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

js怎么实现异步

js怎么实现异步

异步实现方法 JavaScript中实现异步操作主要通过以下几种方式: Promise Promise是ES6引入的异步解决方案,用于处理异步操作的成功或失败状态。 const promise =…

js 实现跳转

js 实现跳转

使用 window.location.href 进行跳转 通过修改 window.location.href 可以跳转到指定 URL,浏览器会加载新页面: window.location.hre…

js计算器的实现

js计算器的实现

实现基础结构 HTML部分需要创建计算器的基本框架,包含显示区域和按钮。使用<div>容器包裹整个计算器,内部设置一个显示屏和多个按钮。 <div class="calculato…