Skip to content

42. Throttling

Biswajit Sundara edited this page Aug 18, 2023 · 2 revisions

Throttling is a technique that controls the rate at which a function is executed.

  • It ensures function is called at maximum frequency
  • And prevents from being executed more than the specified time.
  • This is useful in scenario where events fire rapidly like scrolling and resize.
  • It optimizes performance and avoids overwhelming function calls

There are two common approaches : using a time-based throttling function and setTimeout function.

1. Time-based Throttling Function

  • Here throttle function takes the argument as function & the time to delay
  • It returns a new function that will only execute the original function only in certain interval
  • It compares the now time & the last call, if it exceeds the delay time then time is elapsed and executes the function.
function throttle(fn, delay) {
  let lastCall = 0;

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

    if (now - lastCall >= delay) {
      fn.apply(this, args);
      lastCall = now;
    }
  };
}

const onScrollThrottled = () => {
  console.log("Throttle function called");
};

const throttledFunction = throttle(onScrollThrottled, 3000);
//html
<div style="height: 200vh; background-color: brown">Scroll down to see the effect</div>
window.addEventListener("scroll", throttledFunction);

2. Using SetTimeout

We can achieve throttling by using setTimeout function to delay the execution of a function

  • The throttle function uses a timeoutId to keep track of whether the function is currently waiting to execute.
  • If the function is not waiting (timeoutId=null) then a new timeout is set and the original function is executed with a delay.
function throttle(fn, delay) {
  let timeoutId;

  return function (...args) {
    if (!timeoutId) {
      timeoutId = setTimeout(() => {
        fn.apply(this, args);
        timeoutId = null;
      }, delay);
    }
  };
}

3. Scenarios

The throttle function is used where we want to control the rate of execution of a function

  • Especially when events occur rapidly.
  • Scrolling - Control the rate of scroll events when user scrolls the page up/down
  • Mouse movement tracking - Mouse movement interactions like hover
  • Drag and drop events - Updates to element position happens at controlled rate during dragging
  • Infinite Scrolling - When new content is loaded

4. Difference between debouncing & throttling?

Both debouncing and throttling serve to manage the frequency of function execution

  • But they are suited to different types of interactions.
  • Debouncing is more focused on waiting for a pause before executing a function,
  • while throttling limits the execution rate to a specific interval, ensuring smoother performance in certain scenarios.

Clone this wiki locally