TypeScript与JavaScript封装事件的防抖与节流

防抖和节流都是可以限制短时间内事件的频繁触发导致前端资源开销过大或者对后端服务器造成压力的问题。

1. 防抖

防抖是当事件被频繁触发时,只有最后一次事件会成功执行,一般的实现方式是,每次触发先检查是否有定时器存在,有的话删除定时器,然后重新在定时器中执行那个事件。(用通俗的讲就是,假设A按钮按一次等五秒才会出结果,在五秒内又被按了一次,需要再等五秒才能执行事件,有网友说:就像是英雄联盟里按B的回城被打断了)

适用场景是:搜索框提示,等到用户输入后等待一小段时间再提示,减轻服务端压力。

以下是在项目中使用到的封装代码,首先在utils包下创建一个ts文件:

TypeScript 复制代码
// ts版本:
// eslint-disable-next-line @typescript-eslint/ban-types
export const debounce = (fn: Function, delay: number) => {
  let debounceTimer: NodeJS.Timeout | null;
  return (...args: any[]) => {
    if (debounceTimer) {
      clearTimeout(debounceTimer);
    }
    debounceTimer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};
// ts版本应用,(使用上和javascrpit不一样)
const de = debounce(() => {
  console.log("刷新");
}, 2000);
const reflesh = () => {
  de();
};


// Js版本:
export const debounce = (fn, delay) => {
  let timer = null;
  return (...args) => {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn(this, args);
    }, delay);
  };
};
// Js版本应用:
const click = debounce(() => {
  console.log("点击");
}, 1000);

2.节流

节流是当时间多次被触发时,在指定的单位时间内,只会被触发一次。(就是A按钮被点击后,限定时间内被点击的就无效,类似于我们玩黑魂时,疯狂按鼠标攻击,也只会A一下,需要等到一定时间后才可以A)

使用场景:刷新按钮以及监听滚动获取分页数据。

javascript 复制代码
// 节流, 是在重复的事件请求中,单位时间内只执行一次
// ts版本
// eslint-disable-next-line @typescript-eslint/ban-types
export const throttle = (fn: Function, delay: number): Function => {
  let throttleTimer: NodeJS.Timeout | null;
  return (...args: unknown[]) => {
    if (throttleTimer) {
      return;
    }
    throttleTimer = setTimeout(() => {
      fn.apply(this, args);
      throttleTimer = null;
    }, delay);
  };
};

// ts版本 使用
const th = throttle(() => {
  console.log("刷新");
}, 2000);
const reflesh = () => {
  th();
};

// js版本
export const throttle = (fn, delay) => {
  let timer = null;
  return (...args) => {
    if (timer) {
      return;
    }
    timer = setTimeout(() => {
      fn(this, args);
      timer = null;
    }, delay);
  };
};
//js使用
const click = throttle(() => {
  console.log("点击");
}, 1000);

主要区别还是ts和js对于闭包的使用方式不同。

相关推荐
小李子呢021142 分钟前
前端八股CSS(2)---动画的实现方式
前端·javascript
GreenTea2 小时前
从 Claw-Code 看 AI 驱动的大型项目开发:2 人 + 10 个自治 Agent 如何产出 48K 行 Rust 代码
前端·人工智能·后端
渣渣xiong3 小时前
从零开始:前端转型AI agent直到就业第五天-第十一天
前端·人工智能
布局呆星3 小时前
Vue3 | 组件通信学习小结
前端·vue.js
C澒3 小时前
IntelliPro 企业级产研协作平台:前端智能生产模块设计与落地
前端·ai编程
OpenTiny社区4 小时前
重磅预告|OpenTiny 亮相 QCon 北京,共话生成式 UI 最新技术思考
前端·开源·ai编程
前端老实人灬4 小时前
web前端面试题
前端
Moment5 小时前
AI 全栈指南:NestJs 中的 Service Provider 和 Module
前端·后端·面试
IT_陈寒5 小时前
为什么我的JavaScript异步回调总是乱序执行?
前端·人工智能·后端