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);
相关推荐
無限進步D3 小时前
Java 运行原理
java·开发语言·入门
是苏浙3 小时前
JDK17新增特性
java·开发语言
余人于RenYu3 小时前
Claude + Figma MCP
前端·ui·ai·figma
阿里加多6 小时前
第 4 章:Go 线程模型——GMP 深度解析
java·开发语言·后端·golang
杨艺韬6 小时前
vite内核解析-第2章 架构总览
前端·vite
likerhood6 小时前
java中`==`和`.equals()`区别
java·开发语言·python
我是伪码农7 小时前
外卖餐具智能推荐
linux·服务器·前端
2401_885885047 小时前
营销推广短信接口集成:结合营销策略实现的API接口动态变量填充方案
前端·python
小李子呢02117 小时前
前端八股性能优化(2)---回流(重排)和重绘
前端·javascript
zs宝来了7 小时前
AQS详解
java·开发语言·jvm