节流和防抖分别是什么?在什么场景下使用? 请分别实现一个节流和防抖

115 阅读1分钟

函数节流 (throttle)

在指定的时间间隔内了,只能触发一次函数,如果在指定的时间间隔多次触发函数,只有一次生效

function throttle(fun, delay) {
  let last, deferTimer;
  return function () {
    let that = this;
    let _args = arguments;
    let now = +new Date();
    if (last && now < last + dalay) {
      clearTimeout(deferTimer);
      deferTimer = setTimeout(function () {
        last = now;
        fun.applay(that, _args);
      }, delay);
    } else {
      last = now;
      fun.applay(that, _args);
    }
  };
}