DEV Community

Cover image for Throttling and Debouncing. Avoiding unnecessary API calls.
Martín Mato
Martín Mato

Posted on • Updated on

Throttling and Debouncing. Avoiding unnecessary API calls.

The problem

There are sometimes that we need to perform actions on certain events controlled by the user. This can be the case of events like click, onPress, mouseMove, etc.
A function runs every time any of those events are triggered, and this can happen more time that is necessary, leading to performances issue.
Imagine a type-ahead functionality in a search bar where we have to retrieve the results from an API. If the user types a four-letter word, it calls the API 4 times, but only the last one is essential.
So, how can we prevent those unnecessary calls and potential API calls?

What is Throttling and Debouncing

Throttling

Throttling is a pattern that we can limit the times it fires an event. So, no matter how many times the user can trigger this, it executes only once in a specific time interval.
This technique can be helpful in a case we know the user can abuse clicking a button. We can just let the event trigger for the first time and not let rerun until x milliseconds passed.

Debouncing

Just like Throttling, Debounce limits the times an event fires. The difference is with this technique, no matter how many times the user fires the event, the function will be executed only after a specific time after the last fired.
It means that in the search bar example, the user can type all the four letters. Still, only x milliseconds after the last onPress() call was triggered, the function executes.

Throttling in javascript

Let's see some code. In this case, we will let the user execute a function only every half a second.

let timeout;
const throttle = (func, limit) => {
  if (!timeout) {
    func();
    timeout = setTimeout(function() {
      timeout = undefined;
    }, limit);
  }
};
Enter fullscreen mode Exit fullscreen mode

Examining the code above:

  1. The throttle function receives 2 parameters. First, the function we want to perform and second the interval time expressed in milliseconds.
  2. When throttle executes for the first time, timeout is undefined as is not initialized. Next, we execute the parameter function and schedule a setTimeout that will set timeout to undefined after the limit milliseconds.
  3. As we are checking timeout, the function won't be executed after the setTimeout and timeout is undefined again. This ensure the function is called only once in an interval.

Debouncing in javascript

For this example, we will have a search box. Every user input will trigger an event, but the function will execute after a delay of 0.2 seconds.

let timeout;
var debounce = function(func, delay) {
  clearTimeout(timeout);

  timeout = setTimeout(func, delay);
};
Enter fullscreen mode Exit fullscreen mode
  1. First time debounce function is called, timeout is undefined so clearTimeout does nothing.
  2. We schedule a setTimout to execute the function after a certain delay
  3. If the function is not called again during that period, clearTimeout won't end the execution of timeout and after delay, func executes.

When to use each one?

  • As one of the examples, we can use debounce to control the times an API call to search results due to user input in a case of type-ahead functionality.
  • Also if we have a button or a RefreshControl to force sync data we can limit the times it can be executed using throttle
  • debounce can also be useful in case we need to wait for the user to stop scrolling to the desired place, finish resizing a windows o to capture the last position of a mousemove.

Libraries to the rescue

As you can see, these two techniques are very helpful and they are very utilized in a lot of projects. So is not strange that there are some libraries which implement them. Here are some of them:

// Debounce
searchInput.addEventListener("input", _.debounce(search, 200));

// Throttle
button.addEventListener("click", _.throttle(callToAPI, 500);
});
Enter fullscreen mode Exit fullscreen mode
  • jQuery: There is a project to help us.
// Debounce
$('#searchInput#').keyup($.debounce(200, search));

// Throttle
$('#button#').click($.throttle(500, callToAPI));
Enter fullscreen mode Exit fullscreen mode
  • throttle-debounce: can be found in npm here
// Debounce
searchInput.addEventListener("input", debounce(200, search));

// Throttle
button.addEventListener("click", throttle(500, callToAPI);
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

I hope this helps you to at least be aware of these two great techniques to avoid extra function executions.
Please give me your thoughts in the comments section. I'm always open to suggestions and tips to getting better in this new adventure for me writing this kind of post.
Thanks for reading!.

Top comments (20)

Collapse
 
hontas profile image
Pontus Lundin

Great post! I'm to a big fan of throttling/debouncing and I end up writing my own little helpers over and over.

I'll post my debounce function, happy to get feedback 😅 The benefit in this version is that it accepts arguments and get a proper this-binding when used as event handler - if you're into that sort of thing 😉

const debounce = (func, delay = 200) => {
  let timeoutId;

  return function() {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      func.apply(this, arguments);
    }, delay);
  }
};

function search(evt) {
  console.log(evt.target === this); // true
}

const debouncedSearch = debounce(search, 500);
input.addEventListener("input", debouncedSearch);
Enter fullscreen mode Exit fullscreen mode

Thanks again!

Collapse
 
tomerl101 profile image
Tomer

Great tutorial, I think this is a must for every developer to know it.

Collapse
 
damsalem profile image
Dani Amsalem

I ran into your article at a great time, I was looking at implementing a script based on a screen resize and quickly ran into performance issues.

I will definitely try debouncing or throttling in the near future!

Collapse
 
molly profile image
Molly Struve (she/her)

We recently implemented debounce in DEV and it has been great! Awesome write up!

Collapse
 
otamnitram profile image
Martín Mato

Thanks. I appreciate.

Collapse
 
katylava profile image
katy lavallee

I always get these confused. Thanks for the explanation!

Collapse
 
otamnitram profile image
Martín Mato

You're welcome!

Collapse
 
priyansh2 profile image
Priyansh Agrawal • Edited

I have a question: I am triggering the POST Request on the button click event. The API makes entries in the database. Generally, this API takes 1 sec on average. My problem is that my users can press the button multiple times before completing the API request, which creates numerous resources. I tried putting the pre-check before making any database changes and returning the exception, which is displayed on the UI with an appropriate message. How can I prevent multiple API calls after the first one?

Collapse
 
krmgns profile image
Kerem Güneş

Thanks for sharing the article.
PS, seems the link is broken at: "throttle-debounce: can be found in npm here".

Collapse
 
otamnitram profile image
Martín Mato

Thanks for noticing. Just fixed it.

Collapse
 
lehmannsystems profile image
Mike

This is a great post! THANKS for sharing!!

Collapse
 
hellovietduc profile image
Duc Nguyen

It's so nice to see the definitions explained by a few lines of code! Great article!

Collapse
 
otamnitram profile image
Martín Mato

Thanks!!

Collapse
 
amaelftah profile image
Ahmed Mohamed Abd El Ftah

this is so cool tutorial . thanks a lot for sharing

Collapse
 
obn0x1ous profile image
Nishant Singh

Awesome article. Covers my use case in examples. I will be adding API throttle and Debounce in one of my project

Collapse
 
spock123 profile image
Lars Rye Jeppesen

RxJS

Collapse
 
ruttmann profile image
Marlon Erich Ruttmann

Really simple but very important concepts. Thanks for the post!

Collapse
 
akshay1502 profile image
Akshay Shinde

Really great explanation.

Collapse
 
johncerpa98 profile image
John

func() won't be executed right away with the throttle one, I don't understand.

Collapse
 
otamnitram profile image
Martín Mato

Good catch!. Func() was misplaced. It needs to run if the timeout is undefined but not as a callback of it.