防抖/节流的区别

防抖:
防抖的基本原理是,在指定的时间间隔内,如果连续触发了多次事件,则只执行最后一次事件。
常用于一些需要等待用户停止操作后再执行的场景,比如搜索输入框的自动完成功能。

function debounce(func, delay) {
    
    
  let timeoutId;
  return function() {
    
    
    clearTimeout(timeoutId);
    timeoutId = setTimeout(func, delay);
  }
}
// 使用示例
const handleSearch = () => {
    
    
  // 执行搜索操作
}
const debounceSearch = debounce(handleSearch, 300);
input.addEventListener('input', debounceSearch);

上述代码中,debounce函数接受一个回调函数和延迟时间(单位:毫秒)。在事件触发时,该函数会清除之前的定时器,并创建一个新的定时器,延迟执行回调函数。


节流:
节流的基本原理是,在指定的时间间隔内,连续触发的事件只执行一次。
常用于一些需要限制事件触发频率的场景,比如实时刷新数据、滚动事件等。

function throttle(func, delay) {
    
    
  let lastExecTime = 0;
  
  return function() {
    
    
    const currentTime = Date.now();
    if (currentTime - lastExecTime > delay) {
    
    
      func();
      lastExecTime = currentTime;
    }
  }
}

// 使用示例
const handleScroll = () => {
    
    
  // 处理滚动事件
}

const throttleScroll = throttle(handleScroll, 300);
window.addEventListener('scroll', throttleScroll);

上述代码中,throttle函数接受一个回调函数和时间间隔(单位:毫秒)。在事件触发时,该函数会判断当前时间与上次执行的时间间隔,如果超过了设定的时间间隔,则执行回调函数,并更新执行时间。

区别:防抖只会在最后一次事件后执行触发函数,节流不管事件多么的频繁,都会保证在规定时间段内触发事件函数。

猜你喜欢

转载自blog.csdn.net/to_prototy/article/details/132417865