Skip to content

防抖(Debounce)

js
function debounce(func, wait) {  
  let timeout;  
  return function() {  
    const context = this;  
    const args = arguments;  
    clearTimeout(timeout);  
    timeout = setTimeout(function() {  
      func.apply(context, args);  
    }, wait);  
  };  
}  
  
// 使用示例  
const myEfficientFn = debounce(function() {  
  // 需要防抖执行的函数  
}, 250);  
  
window.addEventListener('resize', myEfficientFn);

节流(Throttle)

javascript
function throttle(func, limit) {  
  let inThrottle;  
  return function() {  
    const context = this;  
    const args = arguments;  
    if (!inThrottle) {  
      func.apply(context, args);  
      inThrottle = true;  
      setTimeout(function() {  
        return inThrottle = false;  
      }, limit);  
    }  
  };  
}  
  
// 使用示例  
const myEfficientFn = throttle(function() {  
  // 需要节流执行的函数  
}, 250);  
  
window.addEventListener('scroll', myEfficientFn);