Skip to main content

Command Palette

Search for a command to run...

Throttleling in JavaScript

Updated
2 min read

The Throttle function bears resemblance to the Debounce function, albeit with nuanced distinctions in its operational behavior. Rather than constraining the frequency at which a function is invoked, the Throttle function curtails the rate at which the function is executed. Specifically, it proscribes execution if the function has been previously summoned within a designated time frame. This ensures that a particular function is executed at a uniform rate, precluding excessive triggering.

Here is the code snippet that demonstrates the implementation of the Throttle function:

function throttle(func, delay) {
  let wait = false;

  return (...args) => {
    if (wait) {
        return;
    }

    func(...args);
    wait = true;
    setTimeout(() => {
      wait = false;
    }, delay);
  }
}

Within this excerpt, the throttle function will invoke the supplied function func, modify a wait variable to true, and subsequently initiate a timer that will revert the wait parameter after the specified delay has elapsed. If the throttle function is called again during this period, it will either invoke the provided function or simply return if the wait parameter remains true.

The Throttle functionality finds applicability in scenarios such as executing a function to modify the layout of a webpage during scrolling. In the absence of a throttle function, the update function would be invoked repeatedly as the user scrolls through the page, potentially leading to significant performance degradation. By employing the throttle function, execution can be restricted to once every specified number of milliseconds (e.g., X milliseconds), thereby enhancing the webpage's responsiveness and efficiency.

The subsequent snippet illustrates how the throttle function can be utilized:

// Define the function responsible for layout modification
function updateLayout() {
  // Implement layout updates...
}

// Instantiate a throttled variant of the function
const throttledUpdateLayout = throttle(updateLayout, 250);

// Register a listener for window scroll events, invoking the throttled function
window.addEventListener("scroll", throttledUpdateLayout);

By crafting the throttleUpdatedLayout function and designating a delay of 250 milliseconds, it can be ensured that the updateLayout function will be executed at most once within each 250-millisecond interval during window scrolling. Should the event be triggered prior to the completion of the delay, no action will be taken. This mechanism fosters a more streamlined and responsive user experience, mitigating the risk of overloading the system with redundant function calls.