重复执行函数
code
function isPromise<T>(val: unknown): val is () => Promise<T> {
return (val !== undefined && val !== null) && typeof val === 'function' && typeof (<{ then?: unknown }>val)?.then === 'function' && typeof (<{ catch?: unknown }>val)?.catch === 'function'
}
export function createAutoTimer<T = unknown, E = unknown>(
fn: () => Promise<T> | T,
stopTrigger: (t: T) => boolean,
timeout = 5000,
immediate = false,
autoClearTimerOnError = true,
onError?: (e: E) => void,
) {
let timer = -1;
let wrapfn = <() => Promise<T>><unknown>null
if (isPromise<T>(fn)) {
wrapfn = fn
} else {
wrapfn = () => new Promise<T>((resolve) => {
resolve(fn())
})
}
const excutor = (immediate: boolean) => {
timer = <number>(<unknown>setTimeout(
() => {
wrapfn().then((t) => {
if (stopTrigger(t)) {
clearTimeout(timer)
} else {
excutor(false)
}
}).catch((e: E) => {
if (autoClearTimerOnError) clearTimeout(timer)
onError?.(e)
})
}
, immediate ? 0 : timeout
));
};
excutor(immediate);
return { cancel: () => clearTimeout(timer) }
}
ts playground demo
