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

相关推荐
TttHhhYy19 小时前
小记,antd design vue的下拉选择框,选项部分不跟着滑动走,固定在屏幕某个部位,来改
前端·vue.js·sql
小二·19 小时前
Python Web 全栈开发实战教程:基于 Flask 与 Layui 的待办事项系统
前端·python·flask
光影少年19 小时前
vite为什么速度快?
前端·学习
万物得其道者成19 小时前
用 Python + MySQL + Web 打造我的私有 Apple 设备监控面板
前端·python·mysql
Hi_kenyon19 小时前
快速入门VUE与JS(二)--getter函数(取值器)与setter(存值器)
前端·javascript·vue.js
海云前端119 小时前
前端面试加分技巧:文本省略 + Tooltip 优雅实现,附可直接复用代码(求职党必看)
前端
在西安放羊的牛油果19 小时前
浅谈 storeToRefs
前端·typescript·vuex
triumph_passion19 小时前
Zustand 从入门到精通:我的工程实践笔记
前端·性能优化
pusheng202519 小时前
双气联防技术在下一代储能系统安全预警中的应用
前端·安全
C_心欲无痕19 小时前
ts - 交叉类型
前端·git·typescript