JS防抖函数

79 阅读1分钟

防抖节流这玩意儿,做校招准备时候背了不下两三次,但确确实实没在实际应用中用到;

先来个开幕雷击:

image.png

emmmm 整吧,工程量大也没办法

话不多说,直接放防抖函数:

/**
 * 防抖函数
 * @fn [Function] 执行的函数
 * @delay [Number] 防抖间隔时间
 * @now [Boolean] 是否立即执行
 */
 export function debounce(fn, now = true, delay = 500) {
  let timer; // 维护一个 timer
  return function() {
    const _this = this; // 取debounce执行作用域的this
    const args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    const curNow = now ? !timer : false;
    timer = setTimeout(function() {
      timer = now ? null : fn.apply(_this, args);
    }, delay);

    if (curNow) fn.apply(_this, args); // 用apply指向调用debounce的对象,相当于_this.fn(args);
  };
}

使用方式:

import { debounce } from './util'

// 原函数
const testFunction = () => { ... }

// 防抖函数
const testFunction = debounce(() => { ... })

over ~