美文网首页
TS对定时器的封装

TS对定时器的封装

作者: 硅谷干货 | 来源:发表于2022-06-20 23:01 被阅读0次

    需求

    因为需要在项目对定时器做统一管理,所以做特定封装,方便维护

    实现

    const timerObj: Record<string, number> = {};
    
    export enum TimerKeys {
      timerId1 = "timerId1",
      timerId2 = "timerId2",
      timerId3 = "timerId3",
    }
    
    // as iOS Method
    export function createScheduled(
      timerId: string,
      callback: Function,
      delay: number = 20
    ) {
      clearInterval(timerObj[timerId]);
      timerObj[timerId] = setInterval(() => {
        callback && callback();
      }, delay);
    }
    
    // 清除指定定时器
    export function clearScheduled(timerId: string) {
      clearInterval(timerObj[timerId]);
    }
    
    // 清除所有定时器
    export function clearAllScheduled() {
      Object.keys(timerObj).forEach((key) => {
        clearInterval(timerObj[key]);
      });
    }
    
    // as Andorid Method
    export function postDelayed(callback: Function, delay: number) {
      let timerId: number | undefined = undefined;
      if (timerId) clearTimeout(timerId);
      timerId = setTimeout(() => {
        clearTimeout(timerId);
        callback && callback();
      }, delay);
    }
    
    // 防抖
    export function debounce(callback: Function, delay: number) {
      let timerId: number | undefined = undefined;
      return function () {
        if (timerId) clearTimeout(timerId);
        timerId = setTimeout(function () {
          clearTimeout(timerId);
          timerId = undefined;
          callback && callback();
        }, delay);
      };
    }
    
    // 节流
    export function throttle(callback: Function, delay: number) {
      let timerId: number | undefined = undefined;
      return function () {
        if (!timerId) return false;
        timerId = setTimeout(function () {
          clearTimeout(timerId);
          timerId = undefined;
          callback && callback();
        }, delay);
      };
    }
    
    

    使用方式

    createScheduled(()=>{
      console.log("xxx")
    }, 1000)
    

    相关文章

      网友评论

          本文标题:TS对定时器的封装

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