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

相关推荐
木易 士心5 分钟前
CSS 中 `data-status` 的使用详解
前端·css
明月与玄武8 分钟前
前端缓存战争:回车与刷新按钮的终极对决!
前端·缓存·回车 vs 点击刷新
牧马少女18 分钟前
css 画一个圆角渐变色边框
前端·css
zy happy41 分钟前
RuoyiApp 在vuex,state存储nickname vue2
前端·javascript·小程序·uni-app·vue·ruoyi
小雨青年1 小时前
Cursor 项目实战:AI播客策划助手(二)—— 多轮交互打磨播客文案的技术实现与实践
前端·人工智能·状态模式·交互
Nan_Shu_6141 小时前
学习:JavaScript(5)
开发语言·javascript·学习
533_1 小时前
[vue3] h函数,阻止事件冒泡
javascript·vue.js·elementui
通往曙光的路上1 小时前
day22_用户授权 头像上传
javascript·vue.js·ecmascript
小光学长1 小时前
基于Vue的儿童手工创意店管理系统as8celp7(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
前端·数据库·vue.js
meichaoWen1 小时前
【Vue】Vue框架的基础知识强化
前端·javascript·vue.js