JavaScript

JavaScript中如何进行事件的节流与防抖

小樊
81
2024-10-27 07:57:00
栏目: 编程语言

在 JavaScript 中,事件节流(throttle)和防抖(debounce)是两种常用的优化高频率触发事件的技术。它们都可以用来控制函数的执行频率,从而提高性能。

1. 事件节流 (Throttle)

事件节流函数会在一定时间内只执行一次目标函数。如果在等待期间再次触发事件,那么重新计时。以下是一个简单的节流函数实现:

function throttle(func, delay) {
  let lastCall = 0;

  return function (...args) {
    const now = Date.now();

    if (now - lastCall < delay) {
      return;
    }

    lastCall = now;
    return func(...args);
  };
}

使用示例:

const throttledFunction = throttle(() => {
  console.log('Throttled function triggered');
}, 300);

window.addEventListener('scroll', throttledFunction);

2. 事件防抖 (Debounce)

事件防抖函数会在一定时间内只执行一次目标函数,如果在等待期间再次触发事件,那么重新计时。防抖的主要应用场景是在用户停止操作后执行一次。以下是一个简单的防抖函数实现:

function debounce(func, delay) {
  let timeout;

  return function (...args) {
    const later = () => {
      timeout = null;
      func(...args);
    };

    clearTimeout(timeout);
    timeout = setTimeout(later, delay);
  };
}

使用示例:

const debouncedFunction = debounce(() => {
  console.log('Debounced function triggered');
}, 300);

window.addEventListener('scroll', debouncedFunction);

总结:

0
看了该问题的人还看了