关于javascript:节流函数与防抖函数

前端常常会遇到间断调用事件的问题,所以节流函数和防抖函数是必不可少的。
我集体通常会在封装通用组件里包裹一层避免事件的反复调用。

节流函数

间接上代码

function throttle(fn, delay) {
  let running = true;
  return function () {
    if (running) {
      fn.apply(this, arguments);
      console.log("arguments", arguments[0]);
      running = false;
      setTimeout(() => {
        running = true;
      }, delay);
    }
  };
}

function needThrottle() {
  console.log("hihihi");
}
const test = throttle(needThrottle, 200);
test(1);
test(2);
test(3);

通过打印出的 arguments[0] 能够看出,执行的是第一次调用的函数。

防抖函数

function debounce(fn, delay) {
  let timer = null;
  return function () {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments);
      console.log('arguments',arguments[0]);
      timer = null;
    }, delay);
  };
}
const debounced = debounce(() => console.log("hi"));
debounced(1);
debounced(2);
debounced(3);

通过打印出的 arguments[0] 能够看出,执行的是最初一次调用的函数。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理