DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

Day 28: Throttling

Throttling ensures that a function is executed at a certain maximum frequency, regardless of how frequently it's called. This is especially useful when dealing with functions that can be invoked rapidly, such as event handlers tied to user interactions like scrolling or resizing the window. Without throttling, these functions might overload the system and lead to performance issues.

Benefits of Throttling:

  1. Performance: Throttling prevents the execution of a function too many times in a short span, reducing the strain on the system and improving overall performance.
  2. Responsiveness: By limiting the execution frequency, throttling maintains the responsiveness of your web application, ensuring it remains smooth and interactive.
  3. Bandwidth Savings: Throttling can also be applied to network-related functions, conserving bandwidth by reducing the number of requests made to the server.

Question

Now, let's get our hands dirty and implement a throttle function from scratch.

function throttle(func, delay) {
// Todo add your code
}

function expensiveCalculation(scrollPos) {
  // Perform the expensive calculations here
  console.log("Calculating for scroll position:", scrollPos);
}

const throttledCalculation = throttle(expensiveCalculation, 300);

window.addEventListener("scroll", function () {
  throttledCalculation(window.scrollY);
});
Enter fullscreen mode Exit fullscreen mode

Hint: We'll use the concept of a timestamp to keep track of the last execution time.

🤫 Check the comment below to see answer.

Top comments (1)

Collapse
 
dhrn profile image
Dharan Ganesan
function throttle(func, delay) {
  let lastExecution = 0;

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

    if (now - lastExecution >= delay) {
      func.apply(this, args);
      lastExecution = now;
    }
  };
}
Enter fullscreen mode Exit fullscreen mode