美文网首页
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对定时器的封装

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

  • ts对axios的简单封装

    在前端项目中,和后台交互获取数据这块,我们通常使用的是axios库,axios是一个基于 promise 的HTT...

  • Easyswoole源码分析-12-定时器

    1.简介 框架对原生的毫秒级定时器进行了封装,以便开发者快速调用 Swoole 的原生定时器,定时器类的命名空间为...

  • 定时器(Quartz) [kwɔːts]

    Quartz定时器就是对java中Timer定时器的封装,支持Cron表达式定时 使用步骤: 1.定义任务类(指定...

  • 状态和生命周期

    学习使用Clock组件,来重用和封装。并设置定时器。封装了一个定时器,如: Try it on CodePen. ...

  • ts通过class类封装axios

    ts通过class类封装axios 一、axios 安装 二、HttpRequest类封装 三、接口方法封装 四、...

  • 移动端自动播放视频之TS视频

    ts简介 TS(Transport Stream,传输流)是一种封装的格式,它的全称为MPEG2-TS。是一种视频...

  • 简单动画原理封装

    封装动画函数 给不同的元素记录不同的定时器

  • iOS GCD定时器封装

    GCD定时器封装 简单调用 [ZFTimer execTask:^{ NSLog(@"1111111 - ...

  • 2019-04-11 图片轮播js

    HTML结构是 首先封装一下getElementById 定时器的设置 功能,鼠标离开main块,会触发定时器 功...

网友评论

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

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