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);
相关推荐
froginwe1110 分钟前
Ruby Dir 类和方法详解
开发语言
比特在路上21 分钟前
蓝桥杯之c++入门(一)【第一个c++程序】
开发语言·c++·职场和发展·蓝桥杯
李游Leo25 分钟前
JavaScript原型链与继承:优化与扩展的深度探索
开发语言·javascript·原型模式
程序员东min26 分钟前
C++:虚函数与多态性习题
开发语言·c++
jimiStephen1 小时前
Go-并行编程新手指南
开发语言·后端·golang
lingllllove1 小时前
PHP中配置 variables_order详解
android·开发语言·php
wn5311 小时前
【浏览器 - Mac实时调试iOS手机浏览器页面】
前端·macos·ios·智能手机·浏览器
游王子1 小时前
Python NumPy(10):NumPy 统计函数
开发语言·python·numpy
master-dragon2 小时前
Java锁自定义实现到aqs的理解
java·开发语言
LCG元2 小时前
Vue.js组件开发-实现HTML内容打印
前端·vue.js·html