JS:防抖与节流函数的实现与应用

一、防抖

防抖:一连串操作只执行一次。通过设置一个延迟时间,如果这段时间没有再次执行操作则运行目标函数,否则重新计时。

下面是一个防抖函数代码:

TypeScript 复制代码
let a=1;
const add = () => {
  a++;
};
const debounce = (fun: Function, delay: number) => {
  let timer: any = null;
  return function () {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fun();
    }, delay);
  };
};
const debounceAdd = debounce(add, 1000);

二、节流

节流:立即执行目标函数,接着设定时间间隔,计时结束后才可再次执行目标函数。

TypeScript 复制代码
let a = 0;
const add = () => {
  a++;
};
const throttle = (fun: Function, delay: number) => {
  let timer: any = null;
  return function () {
    if (!timer) {
      fun();
      timer = setTimeout(() => {
        fun();
        timer = null;
      }, delay);
    }
  };
};
const throttleAdd = throttle(add, 1000);
相关推荐
excel21 小时前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel1 天前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼1 天前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping1 天前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙1 天前
[译] Composition in CSS
前端·css
白水清风1 天前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix1 天前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts
用户22152044278001 天前
new、原型和原型链浅析
前端·javascript
阿星做前端1 天前
coze源码解读: space develop 页面
前端·javascript
叫我小窝吧1 天前
Promise 的使用
前端·javascript