阅读 380

ES6 JS防抖节流实现

防抖

// 定时器方式实现

export const debounce = (fn, delay) =>
  const timer = null;
  return (...param) => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn(...param);
    }, delay);
  };
}
复制代码

// reactHook方式实现

export const useDebounce = (value, delay) => {
  const [debouncedValue, setDebouncedValue] = useState(value);
  useEffect(() => {
    // 每次在value变化以后,设置一个定时器
    const timer = setTimeout(() => setDebouncedValue(value), delay);
    // 每次在上一个useEffect处理完以后再运行
    return () => clearTimeout(timer);
  }, [value, delay]);

  return debouncedValue;
};
复制代码

// 测试

// 需要改变窗口大小
window.onresize = debounce(() => {
  console.log(111);
}, 500);
复制代码

节流

// 定时器方式实现

export const throttle = (fn, delay) =>
  const timer = null;
  return (...params) => {
    if (!timer) {
      timer = setTimeout(() => {
        fn(...params);
        timer = null;
      }, delay);
    }
  };
}
复制代码

// 时间戳方式实现

export const throttle = (fn, delay) =>
  const pre = 0;
  return (...params) => {
    let now = new Date().getTime();
    if (now - pre > delay) {
      fn(...params);
      pre = now;
    }
  };
}
复制代码

// 测试

// 需要改变窗口大小 
window.onresize = throttle(() => { console.log(111); }, 2000);
复制代码
文章分类
前端
文章标签