JavaScriptmediumJavaScript

Throttle Function

Limits a function to be executed only once per specified time period

01

The problem

In continuously triggered events like scrolling, dragging, need to control function execution frequency

02

The solution

JavaScript
function throttle(func, limit) {
  let inThrottle;
  
  return function(...args) {
    if (!inThrottle) {
      func.apply(this, args);
      inThrottle = true;
      setTimeout(() => {
        inThrottle = false;
      }, limit);
    }
  };
}

03

Parameters

funcfunction

Function to throttle

limitnumber

Time limit in milliseconds

04

Put it to work

Example
// Handle scroll events
const handleScroll = throttle(() => {
  console.log('Scrolling...');
}, 1000);

window.addEventListener('scroll', handleScroll);