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);
相关推荐
liulilittle5 分钟前
C++ 浮点数封装。
linux·服务器·开发语言·前端·网络·数据库·c++
wordbaby16 分钟前
Expo 进阶指南:赋予 TanStack Query “原生感知力” —— 深度解析 AppState 与 NetInfo
前端·react native
Moment22 分钟前
从美团全栈化看 AI 冲击:前端转全栈,是自救还是必然 🤔🤔🤔
前端·后端·面试
天问一30 分钟前
使用 Vue Router 进行路由定制和调用的示例
前端·javascript·vue.js
失散1341 分钟前
Python——1 概述
开发语言·python
萧鼎44 分钟前
Python 图像哈希库 imagehash——从原理到实践
开发语言·python·哈希算法
小小8程序员1 小时前
STL 库(C++ Standard Template Library)全面介绍
java·开发语言·c++
立志成为大牛的小牛1 小时前
数据结构——五十六、排序的基本概念(王道408)
开发语言·数据结构·程序人生·算法
老王熬夜敲代码1 小时前
C++中的atomic
开发语言·c++·笔记·面试
a努力。2 小时前
腾讯Java面试被问:String、StringBuffer、StringBuilder区别
java·开发语言·后端·面试·职场和发展·架构