export const setSafeInterval = (
fn: <TData>() => Promise<TData>,
timer: number,
option?: {
retry: number | boolean;
}
) => {
let t: TimerType | undefined;
let retryCount = 0;
const _interval = async (timer: number) => {
retryCount++;
try {
await fn();
t = setTimeout(() => {
clearTimeout(t as TimerType);
_interval(timer);
}, timer);
} catch (error) {
console.error(error);
if (
option?.retry === true ||
(typeof option?.retry === 'number' && option?.retry >= retryCount)
) {
//判断是否需要重试
t = setTimeout(() => {
_interval(timer);
}, timer);
}
}
};
_interval(timer);
return {
stop: () => {
clearTimeout(t as TimerType);
t = undefined;
},
start: (timer = 1000) => {
_interval(timer);
},
getTimer: () => {
return t;
},
};
};
网友评论