防抖节流

7 阅读1分钟

防抖

触发事件后延迟一定时间执行,如果在延迟时间内又触发了,就重置延迟时间

<body>
  <input type="text">
</body>
<script>
  document.querySelector('input').oninput = debounce(function() {
    console.log('防抖')
  })
</script>
// 基础示例
function debounce(fn) {
  let timer = null;
  return function (...args) {
    console.log(args)
    if (timer) {
      clearTimeout(timer);
      timer = null
    }
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, 1000);
  };
}

节流

频繁触发事件,每间隔一定时间执行一次

// 基础示例
function throttle(fn) {
  let timer = null;
  return function (...args) {
    if (timer) return
    timer = setTimeout(() => {
      console.log(args)
      fn.apply(this, args);
      clearTimeout(timer);
      timer = null;
    }, 2000);
  };
}

window.onscroll = throttle(function() {
  console.log(1)
})