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

相关推荐
灵感__idea3 小时前
Hello 算法:让前端人真正理解算法
前端·javascript·算法
向葭奔赴♡3 小时前
CSS是什么?—— 网页的“化妆师”
前端·css
黑犬mo3 小时前
在Edge、Chrome浏览器上安装uBlock Origin插件
前端·edge
excel3 小时前
🧩 Vue 3 watch 源码详解(含完整注释)
前端·javascript·vue.js
大前端helloworld3 小时前
前端梳理体系从常问问题去完善-网络篇
前端·面试
excel4 小时前
🌿 一文看懂 Vue 3 的 watch 源码:从原理到流程
前端
繁依Fanyi4 小时前
让工具说话:我在 Inspira Board 里用 AI 把“能用、好用、可复用”落成了日常
前端
weixin_456904275 小时前
C# 中的回调函数
java·前端·c#
kura_tsuki5 小时前
[Web网页] LAMP 架构与环境搭建
前端·架构
yinuo6 小时前
UniApp+Vue3多分包引入同一 npm 库被重复打包至 vendor 的问题分析与解决
前端