美文网首页
setSafeInterval

setSafeInterval

作者: _嘿嘿_ | 来源:发表于2023-02-01 09:20 被阅读0次
    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;
        },
      };
    };
    
    

    相关文章

      网友评论

          本文标题:setSafeInterval

          本文链接:https://www.haomeiwen.com/subject/nvsmhdtx.html