热搜:m1 nginx 代理 前端

前端开发中防抖的实现方法

2024-04-01 09:30:01

防抖是频繁操作的最后时刻触发。比如输入停止后一段时间没有再输入才会请求接口。

前端开发中防抖的实现方法 1

// 定时器版
function debounce (fn, delay = 100) {
  let timer = null;
  return function(...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.call(this, ...args);
      timer = null;
    }, delay)
  }
}
// 使用
input.addEventListener('keyup', debounce(function() {
  console.log(input.value);
}, 300));