防抖函数的作用是当用户触发某个事件时,只有在事件停止触发一段时间后才会执行函数,以避免函数被频繁调用。

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

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

这个函数接受两个参数:需要执行的函数和延迟时间。它返回一个新的函数,这个新函数使用了闭包来保存了需要执行的函数和延迟时间。每次新函数被调用时,它会清除之前设置的计时器,然后重新设置一个新的计时器,在延迟时间之后执行需要执行的函数。如果在延迟时间内新函数又被调用,之前设置的计时器会被清除并重新设置一个新的计时器,以避免函数被频繁调用。

使用方法:

function doSomething() {
  console.log('Hello World!');
}

const debouncedDoSomething = debounce(doSomething, 1000);

debouncedDoSomething(); // 1秒后输出 "Hello World!"
debouncedDoSomething(); // 又等待1秒后输出 "Hello World!"
写一个防抖js函数

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

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