js实现poll函数


实现 Poll 函数的方法
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: 要执行的函数,返回一个值或Promisecondition: 判断是否满足条件的函数,接收fn的结果作为参数interval: 轮询间隔时间,默认为1000mstimeout: 超时时间,默认为30000ms
这些实现提供了灵活的轮询机制,可以根据具体需求选择合适的方法。






