防抖函数的作用是在事件被触发n秒后再执行回调函数,如果在这n秒内又触发了该事件,则重新计时。

下面是一个简单的防抖函数实现:

function debounce(func, delay) {
  let timer = null;
  return function() {
    const context = this;
    const args = arguments;
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(context, args);
    }, delay);
  };
}

这个函数接受两个参数:

  • func:要执行的回调函数
  • delay:防抖延迟的时间

它返回一个新的函数,使用了闭包保存了timer变量,用于记录延迟的时间。

每次调用这个函数时,它会清除之前的timer,然后重新设置一个新的,延迟delay秒后执行回调函数。如果在这段时间内又调用了该函数,则重新计时,直到延迟时间结束才执行回调函数

实现一个防抖函数

原文地址: https://www.cveoy.top/t/topic/huah 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录