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);

Clone this wiki locally