一级标题
export const createPolling = (interval: number, fn = noop) => {
let timerId: number | undefined;
let n = 0;
let execId = "";
let exeFn: AnyFunction | undefined = fn;
return {
duration: 0,
get isRunning() {
return !!execId;
},
stopped(id: string) {
return id !== execId;
},
_run() {
const st = Date.now();
this.duration = st - n;
const runId = execId;
const exec = (t: number) => {
timerId = window.setTimeout(() => {
if (this.stopped(runId)) {
return;
}
this._run();
}, t);
};
const ret: any = exeFn?.();
if (ret && ret.then && isFunction(ret.then)) {
ret.then(() => {
const timeDiff = Date.now() - st;
const intervalRemain = Math.max(0, interval - timeDiff);
if (this.stopped(runId)) {
return;
}
exec(intervalRemain);
});
} else {
exec(interval);
}
},
immediateRun() {
exeFn?.();
},
start(sfn?: (...p: any[]) => void) {
n = Date.now();
this.duration = 0;
execId = uniqueId("__FE_POLLING_EXEC_ID__");
clearTimeout(timerId);
if (sfn) {
exeFn = sfn;
}
this._run();
},
stop() {
execId = "";
if (timerId !== undefined) {
clearTimeout(timerId);
timerId = undefined;
}
},
destroy() {
exeFn = undefined;
this.stop();
},
};
};
使用
import { createPolling } from '@/utils/utils';
const poll = createPolling(5000, () => { getCurrentData() });
poll.start();
onBeforeUnmount(() => {
poll.stop();
})