前端防抖与节流

直接上代码

一、js

防抖
export function debounce(fn, time, immediate) {
  let timer = null;
  const debounced = function () {
    const context = this;
    const args = arguments;
    if (timer) clearTimeout(timer); // 清除前一个定时器
    if (immediate) {
      // 为true立即执行
      const callNow = !timer;
      timer = setTimeout(() => {
        timer = null;
      }, time || 500);
      if (callNow) fn.apply(context, args);
    } else {
      // 非立即执行
      timer = setTimeout(function () {
        fn.apply(context, args);
      }, time || 500);
    }
  };
  debounced.cancel = function () {
    // 取消防抖
    clearTimeout(timer);
    timer = null;
  };
  return debounced;
}
节流
/**
 * 节流throttle:所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数。
 * 节流会稀释函数的执行频率。
 * @param {Function} func 执行函数
 * @param {Number} wait 毫秒数
 * @param {boolean} [immediate=true] 是否立刻执行
 * @returns
 */
function throttle(func, wait, immediate = true) {
  let prevTime = 0;
  let first = true;
  const execu = ({ currentTime, context, args }) => {
    if (currentTime >= prevTime) {
      func.apply(context, args);
      first = true;
    }
  };
  const reset = (currentTime) => {
    if (first) {
      prevTime = currentTime + wait;
      first = false;
    }
  }
  return function () {
    const context = this;
    const args = arguments;
    const currentTime = Date.now();
    if (immediate) {
      execu({ currentTime, context, args });
      reset(currentTime);
    } else {
      reset(currentTime);
      execu({ currentTime, context, args });
    }
  }
}

二、Ts

防抖

type DebounceFunction<T extends any[]> = (...args: T) => void;

function debounce<T extends any[]>(
  func: (...args: T) => void,
  wait: number,
  immediate: boolean = false
): DebounceFunction<T> {
  let timeout: number | undefined;
  return function (this: unknown, ...args: T) {
    const context = this;
    const later = () => {
      timeout = undefined;
      if (!immediate) func.apply(context, args);
    };
    const callNow = immediate && timeout === undefined;
    clearTimeout(timeout);
    timeout = window.setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
}

节流

type ThrottleFunction<T extends any[]> = (...args: T) => void;

function throttle<T extends any[]>(
  func: (...args: T) => void,
  wait: number,
  immediate: boolean = true
): ThrottleFunction<T> {
  let lastTime: number = 0;
  let timeout: number | undefined;
  
  return function (this: unknown, ...args: T) {
    const context = this;
    const now = Date.now();

    const later = () => {
      lastTime = immediate ? Date.now() : 0;
      timeout = undefined;
      if (!immediate) func.apply(context, args);
    };

    if (immediate && timeout === undefined) {
      func.apply(context, args);
      lastTime = Date.now();
    }

    if (timeout !== undefined) return;

    const remaining = wait - (now - lastTime);
    if (remaining <= 0 || remaining > wait) {
      if (!immediate) func.apply(context, args);
      lastTime = now;
    } else {
      timeout = window.setTimeout(later, remaining);
    }
  };
}

如何使用

 const fun1 = debounce(()=>{  函数内容 },500,true)  // 防抖
三个参数分别代表
1. 要防抖/节流的函数
2. 间隔时间
3. 是否立即执行
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值