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对于闭包的使用方式不同。

相关推荐
p***h64314 分钟前
JavaScript在Node.js中的异步编程
开发语言·javascript·node.js
N***738529 分钟前
Vue网络编程详解
前端·javascript·vue.js
e***716730 分钟前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
程序猿小蒜32 分钟前
基于springboot的的学生干部管理系统开发与设计
java·前端·spring boot·后端·spring
银空飞羽32 分钟前
让Trae CN SOLO自主发挥,看看能做出一个什么样的项目
前端·人工智能·trae
Eshine、1 小时前
解决前端项目中,浏览器无法正常加载带.gz名称的文件
前端·vue3·.gz·.gz名称的js文件无法被加载
q***38512 小时前
TypeScript 与后端开发Node.js
javascript·typescript·node.js
用户47949283569152 小时前
别再当 AI 的"人肉定位器"了:一个工具让 React 组件秒定位
前端·aigc·ai编程
Nan_Shu_6142 小时前
学习:Sass
javascript·学习·es6
WYiQIU3 小时前
面了一次字节前端岗,我才知道何为“造火箭”的极致!
前端·javascript·vue.js·react.js·面试