添加防抖函数

38 阅读1分钟

记录下防抖函数的使用:

函数防抖(debounce),就是指触发事件后,在 n 秒内函数只能执行一次,如果触发事件后在 n 秒内又触发了事件,则会重新计算函数延执行时间(在这里和函数节流区分一下,函数节流是在触发完事件之后的一段时间之内不能再次触发事件)。

调用方法:const sendReviewAction = debounce(() => {},2000)

const debounce = (fn, time) => {
  let timer: any = null;
  return (...args) => {
    const context = this;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.call(context, ...args);
    }, time);
  };
};