DEV Community

Dileep Reddy
Dileep Reddy

Posted on • Updated on

What is Throttling? How to implement it in JS?

In the previous post we talked about debounce. Click on this link if you'd like to know about debouncing.


Throttling is a method used to limit the number of times a function can be executed.

Throttling - No matter how many times a function is fired, it will be executed only once in a given time interval

Let's say we have an expensive function which does heavy computation or calls a costly 3rd party API.

const expensive = () => {
  console.log('Expensive function');
}
Enter fullscreen mode Exit fullscreen mode

We can limit the number of times the function can be executed by using throttling. Let's write a simple throttle function.

const throttle = (fn, delay) => {
  let wait = false;

  const throttledFunction = () => {
    if (wait) return; // If wait is true, it means the timer
// is still running and the function shouldn't be executed

    fn();
    wait = true;
    setTimeout(() => {
      wait = false;
    }, delay);

  return throttledFunction;
}

const inExpensive = throttle(expensive, 1000);
Enter fullscreen mode Exit fullscreen mode

Our throttle function takes a callback function and delay and returns its throttled counterpart(inExpensive).

But wait, our throttle function cannot handle arguments. Let's improve it a bit so that it can take arguments.

const throttle = (fn, delay) => {
  let wait = false;
  let storedArgs = null;

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

    fn(...storedArgs);
    wait = true;
    setTimeout(() => {
      wait = false;
    }, delay);
  }

  return throttledFunction;
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading!....

https://medium.com/walkme-engineering/debounce-and-throttle-in-real-life-scenarios-1cc7e2e38c68
https://www.freecodecamp.org/news/javascript-debounce-example/
https://egghead.io/lessons/javascript-build-lodash-debounce-from-scratch

Top comments (0)