当前位置:首页 > JavaScript

js 实现轮询

2026-04-05 10:27:18JavaScript

轮询的基本概念

轮询是一种客户端定期向服务器发送请求以获取最新数据的技术。适用于需要实时更新但无法使用WebSocket等长连接方案的场景。

简单轮询实现

使用setInterval创建定时器,定期发送请求:

function simplePolling(url, interval) {
  setInterval(() => {
    fetch(url)
      .then(response => response.json())
      .then(data => console.log('Updated data:', data))
      .catch(err => console.error('Polling error:', err));
  }, interval);
}

// 使用示例
simplePolling('/api/data', 3000); // 每3秒请求一次

带错误处理的增强版轮询

增加网络错误处理和请求超时控制:

function enhancedPolling(url, interval, timeout = 5000) {
  const controller = new AbortController();
  const signal = controller.signal;

  const poll = () => {
    setTimeout(() => controller.abort(), timeout);

    fetch(url, { signal })
      .then(response => {
        if (!response.ok) throw new Error(response.statusText);
        return response.json();
      })
      .then(data => {
        console.log('New data:', data);
        setTimeout(poll, interval);
      })
      .catch(err => {
        console.error('Polling failed:', err);
        setTimeout(poll, interval * 2); // 错误时延长间隔
      });
  };

  poll();
}

指数退避策略

网络不稳定时采用指数退避算法:

function exponentialBackoffPolling(url, maxInterval = 30000) {
  let attempts = 0;
  const baseInterval = 1000;

  const poll = () => {
    const delay = Math.min(baseInterval * Math.pow(2, attempts), maxInterval);

    setTimeout(() => {
      fetch(url)
        .then(response => {
          if (!response.ok) throw new Error(response.statusText);
          attempts = 0;
          return response.json();
        })
        .then(data => {
          console.log('Data update:', data);
          poll();
        })
        .catch(err => {
          console.error(`Attempt ${attempts + 1} failed:`, err);
          attempts++;
          poll();
        });
    }, delay);
  };

  poll();
}

终止轮询的方法

需要停止轮询时可以使用以下方式:

js 实现轮询

let pollingInterval;

function startPolling() {
  pollingInterval = setInterval(() => {
    fetch('/api/data')
      .then(/* ... */);
  }, 2000);
}

function stopPolling() {
  clearInterval(pollingInterval);
}

实际应用建议

  • 重要数据轮询间隔建议不低于30秒
  • 配合ETag或Last-Modified头减少不必要的数据传输
  • 页面隐藏时(通过Visibility API)应暂停轮询
  • 考虑使用Service Worker管理后台轮询

以上实现方案可根据具体需求组合使用,比如在简单轮询基础上增加错误处理和退避策略。

标签: js
分享给朋友:

相关文章

js实现轮播图

js实现轮播图

轮播图实现方法 基础HTML结构 <div class="slider"> <div class="slides"> <img src="image1.jpg…

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽功能。以下是核心代码逻辑: const draggableElement = document.…

js实现打印

js实现打印

使用window.print()方法实现打印 在JavaScript中,可以通过调用window.print()方法直接触发浏览器的打印功能。这会打开系统的打印对话框,用户可以选择打印机和设置打印选项…

js实现全选

js实现全选

实现全选功能的方法 在JavaScript中实现全选功能通常涉及监听全选复选框的点击事件,并根据其状态控制其他复选框的选中状态。以下是几种常见的实现方式: 基础DOM操作实现 通过获取所有目标复选框…

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…

js实现预览

js实现预览

文件上传预览实现 使用JavaScript实现文件上传预览功能,可以通过FileReader对象读取文件内容并显示预览。以下代码支持图片、文本和PDF文件的预览: // HTML部分需要包含…