当前位置:首页 > JavaScript

js实现轮询

2026-03-14 08:02:28JavaScript

轮询的基本概念

轮询(Polling)是一种客户端定期向服务器发送请求以获取最新数据的技术。适用于实时性要求不高或无法使用WebSocket等长连接的场景。

使用 setInterval 实现基础轮询

通过 setInterval 定时发起请求,适合简单场景:

function pollServer() {
    fetch('/api/data')
        .then(response => response.json())
        .then(data => console.log('Data:', data))
        .catch(error => console.error('Polling error:', error));
}

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

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

使用 setTimeout 实现递归轮询

更灵活的递归方式,可动态调整间隔或根据条件停止:

function pollServer() {
    fetch('/api/data')
        .then(response => response.json())
        .then(data => {
            console.log('Data:', data);
            if (data.needsUpdate) {
                setTimeout(pollServer, 1000); // 数据需要更新时加快轮询
            } else {
                setTimeout(pollServer, 5000); // 否则恢复默认间隔
            }
        })
        .catch(error => {
            console.error('Polling error:', error);
            setTimeout(pollServer, 10000); // 出错时延长间隔
        });
}

pollServer(); // 启动首次轮询

带退避策略的轮询

网络异常时采用指数退避(Exponential Backoff)减少请求压力:

let retryCount = 0;
const MAX_RETRIES = 5;
const BASE_DELAY = 1000;

function pollServerWithBackoff() {
    fetch('/api/data')
        .then(response => {
            if (!response.ok) throw new Error('Server error');
            return response.json();
        })
        .then(data => {
            retryCount = 0; // 重置重试计数
            console.log('Data:', data);
            setTimeout(pollServerWithBackoff, 5000);
        })
        .catch(error => {
            if (retryCount < MAX_RETRIES) {
                const delay = BASE_DELAY * Math.pow(2, retryCount);
                retryCount++;
                console.warn(`Retrying in ${delay}ms...`);
                setTimeout(pollServerWithBackoff, delay);
            } else {
                console.error('Max retries reached');
            }
        });
}

pollServerWithBackoff();

结合 AbortController 控制轮询终止

通过 AbortController 实现请求取消,避免内存泄漏:

js实现轮询

const abortController = new AbortController();

function controlledPolling() {
    fetch('/api/data', { signal: abortController.signal })
        .then(response => response.json())
        .then(data => {
            console.log('Data:', data);
            setTimeout(controlledPolling, 3000);
        })
        .catch(error => {
            if (error.name === 'AbortError') {
                console.log('Polling stopped');
            } else {
                console.error('Error:', error);
                setTimeout(controlledPolling, 3000);
            }
        });
}

controlledPolling();

// 终止轮询
// abortController.abort();

注意事项

  • 性能影响:高频轮询会增加服务器负载,需合理设置间隔时间。
  • 竞态条件:确保前一次请求完成后再发起下一次请求,避免响应顺序错乱。
  • 替代方案:对于高实时性需求,建议考虑WebSocket或Server-Sent Events(SSE)。

标签: js
分享给朋友:

相关文章

js实现倒计时

js实现倒计时

实现倒计时的基本方法 使用 JavaScript 实现倒计时功能可以通过 setInterval 或 setTimeout 结合日期计算来完成。以下是几种常见的实现方式: 使用 setInterva…

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https://…

js实现日历

js实现日历

实现日历的基本思路 使用JavaScript实现日历的核心是动态生成日期表格,并处理月份切换逻辑。需要计算当前月的天数、起始星期几,并动态渲染到页面上。 获取当前日期信息 通过Date对象获取当前年…

js实现复制功能

js实现复制功能

使用 document.execCommand 方法 这种方法适用于较旧的浏览器,但在现代浏览器中可能被逐步淘汰。通过创建一个临时的 textarea 元素,将文本内容放入其中,然后执行复制命令。…

js实现图片放大缩小

js实现图片放大缩小

实现图片放大缩小的基础方法 使用CSS的transform: scale()属性可以快速实现图片的放大缩小效果。通过JavaScript动态修改该属性值: const img = document.…

js实现换肤

js实现换肤

使用CSS变量实现换肤 通过CSS变量可以轻松实现主题切换功能。CSS变量在根元素中定义,通过JavaScript动态修改这些变量值。 :root { --primary-color: #349…