当前位置:首页 > JavaScript

js实现poll函数

2026-04-07 12:45:36JavaScript

实现 Poll 函数的方法

Poll 函数通常用于轮询某个条件或状态,直到满足特定条件或超时。以下是几种实现方式:

js实现poll函数

基本实现

function poll(fn, condition, interval = 1000, timeout = 30000) {
  const endTime = Date.now() + timeout;

  const checkCondition = (resolve, reject) => {
    Promise.resolve(fn())
      .then(result => {
        if (condition(result)) {
          resolve(result);
        } else if (Date.now() < endTime) {
          setTimeout(checkCondition, interval, resolve, reject);
        } else {
          reject(new Error('Polling timeout'));
        }
      })
      .catch(reject);
  };

  return new Promise(checkCondition);
}

使用 async/await 的实现

async function poll(fn, condition, interval = 1000, timeout = 30000) {
  const endTime = Date.now() + timeout;

  while (Date.now() < endTime) {
    const result = await fn();
    if (condition(result)) return result;
    await new Promise(resolve => setTimeout(resolve, interval));
  }

  throw new Error('Polling timeout');
}

带取消功能的实现

function cancellablePoll(fn, condition, interval = 1000, timeout = 30000) {
  let timer;
  let cancelled = false;

  const promise = new Promise((resolve, reject) => {
    const endTime = Date.now() + timeout;

    const checkCondition = () => {
      if (cancelled) {
        reject(new Error('Polling cancelled'));
        return;
      }

      Promise.resolve(fn())
        .then(result => {
          if (condition(result)) {
            resolve(result);
          } else if (Date.now() < endTime) {
            timer = setTimeout(checkCondition, interval);
          } else {
            reject(new Error('Polling timeout'));
          }
        })
        .catch(reject);
    };

    checkCondition();
  });

  promise.cancel = () => {
    cancelled = true;
    clearTimeout(timer);
  };

  return promise;
}

使用示例

// 示例:轮询直到某个元素出现在DOM中
poll(
  () => document.querySelector('.target-element'),
  element => element !== null,
  500,
  5000
)
  .then(element => console.log('Element found:', element))
  .catch(err => console.error('Polling failed:', err));

参数说明

  • fn: 要执行的函数,返回一个值或Promise
  • condition: 判断是否满足条件的函数,接收fn的结果作为参数
  • interval: 轮询间隔时间,默认为1000ms
  • timeout: 超时时间,默认为30000ms

这些实现提供了灵活的轮询机制,可以根据具体需求选择合适的方法。

标签: 函数js
分享给朋友:

相关文章

js实现拷贝

js实现拷贝

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

uniapp如何写全局函数

uniapp如何写全局函数

全局函数的定义与使用 在UniApp中定义全局函数可以通过挂载到Vue.prototype或使用模块化导出导入的方式实现。以下是两种常用方法: 方法一:挂载到Vue.prototype 在main.…

利用js实现

利用js实现

使用 JavaScript 实现 在 JavaScript 中,可以通过多种方式实现功能,具体取决于需求。以下是几种常见的方法: 方法一:使用原生 JavaScript // 示例代码…

js实现vue路由

js实现vue路由

Vue 路由的基本实现 在 Vue.js 中实现路由功能通常使用 Vue Router 库。Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue R…

js实现密码

js实现密码

密码强度验证 使用正则表达式验证密码强度是一种常见方法。以下代码检查密码是否包含大小写字母、数字和特殊字符,且长度至少为8位: function checkPasswordStrength(pass…

js实现正交

js实现正交

正交的概念 正交在数学和计算机科学中通常指两个向量垂直或线性无关。在编程中,正交性常被用于设计模块化、低耦合的系统。 向量正交判断 判断两个向量是否正交可以通过点积是否为0来实现: functio…