手写 防抖函数 debounce

1.封装

某个函数在短时间内只执行最后一次

意思也就是说,函数被触发时,需要先延迟,在延迟的时间内,如果再次被触发,则取消之前的延迟,重新开始延迟。这样就能达到,只响应最后一次,其余的请求都过滤掉。

这种处理方式有很多实际的应用场景:比如对输入框数据的校验处理,没必要每输入一个字符就校验一遍;

var self = {
  // 防抖
  _debounce(fn, delay) {
    let timer = null;

    return function () {
      let args = arguments;
      let context = this;

      if (timer) {
        clearTimeout(timer);

        timer = setTimeout(function () {
          fn.apply(context, args);
        }, delay);
      } else {
        timer = setTimeout(function () {
          fn.apply(context, args);
        }, delay);
      }
    };
  },
};

module.exports = self;

2.调用

import commonFunc from "UTIL/commonFunc";

handleSearch = commonFunc._debounce((value) => {
  console.log(value)
}, 300);

.

原文地址:https://www.cnblogs.com/crazycode2/p/13345557.html