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);
相关推荐
zbguolei1 分钟前
第002篇 · 战火中的电子黎明
开发语言·php
用户88956195481716 分钟前
戴上眼镜就把今天听完:绿光快报的 AIUI 语音新闻智能体
javascript
sean_wang128 分钟前
Rust 轻量级虚拟机 smolvm 实战:200ms 冷启动、OCI 镜像直跑、单文件打包
开发语言·后端·rust·大鲸华章
lisw0512 分钟前
前端:概念、历史、内容、挑战与展望!
前端
stormsha16 分钟前
ResizeObserver loop completed with undelivered notifications:它只是个警告,但也是你代码的供词
javascript·css
战6171 小时前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法
ZHOUPUYU1 小时前
PHP 现代工程实践:从语言特性到高性能 Web 应用构建
android·前端·php
郝学胜-神的一滴1 小时前
量化交易从入门到精通 05:策略从哪来
开发语言·python·numpy·pandas·scikit-learn·matplotlib·scipy
Nazarick2 小时前
从 fetch 到 then:Demo在线订单系统 Ajax 回调的逐帧拆解
java·javascript·ajax·web
zbguolei2 小时前
第001篇 · 算盘与差分机
开发语言·php