All about Throttling vs Debouncing!!

Yash Soni
4 min readJun 24, 2020

One of the most common and important interview questions, if you’re appearing for the position of a UI developer. Big tech companies like Uber, Facebook, PayTm usually ask questions around this and tests your knowledge.

Both are separate concepts but works very closely and it is very important to know, when to use which and what are there use cases.

Both are widely used for Performance enhancement, rating limiting the execution of the function, API calls, load on the server and to improve the overall user experience.

Let’s start…

Throttling

Calling function after a certain period of the time interval. It ensures a function is run regularly at a fixed rate & prevents a function from running if it has run “recently”. The most common use cases are Resizing of the window, clicking multiple buttons, and Video Game.

Throttling is a technique in which, doesn’t matter how many times the user fires the event, the attached function will be executed only once in a given time interval.

How to implement it?

setTimeout()
The first option and the one that’s been used for quite a while is to use setTimeout to schedule the next callback at a certain point in the future. This would ensure that it isn’t called too frequently. For instance, if I wanted to listen to the scroll event, and throttle any calls it makes to a custom function so that the function is not called more than once every 16ms, I could do something like this:

# A generic function that takes a callback function and time as its arguments. This helper function could then be used to throttle whatever function you want without writing additional code for each one.
function throttle (callback, limit) {
var tick = false;
return function () {
if (!tick) {
callback.call();
tick = true;
setTimeout(function () {
tick = false;
}, limit);
}
}
}
window.addEventListener(“scroll”, throttle(customFunction, 16));

requestAnimationFrame()
Another option that we have at our disposal is the requestAnimationFrame (rAF) route. This is especially helpful when the function we want to throttle is connected with animation or anything that will be painting to the screen. This is similar to the setTimeout option above, but instead of setting a specific number of ms to wait, we simply pass it to the browser to be processed on the next frame, whenever that may be.

var lastScrollPosition = 0,
tick = false; // Track whether call is currently in process
function customFunction (scrollPos) {
// Custom function that does something
// based on the scroll position
}
window.addEventListener(‘scroll’, function(e) {
lastScrollPosition = window.scrollY;
if (!tick) {
window.requestAnimationFrame(function() {
doSomething(lastScrollPosition);
tick = false;
});
tick = true;
}
});

Debouncing

Calling a function only if a keypress difference between the indifference of a certain period of a time interval. It also a function that ensures that it doesn’t get called too frequently. The most common use cases are searching and Scrolling.

In the debouncing technique, it doesn’t matter how many times the user fires the event, the attached function will be executed only after the specified time once the user stops firing the event.

How to implement it?
Here’s the basic JavaScript debounce function (as taken from Underscore.js):

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};

You’ll pass the debounce function the function to execute and the fire rate limit in milliseconds. Here’s an example usage:

var myEfficientFn = debounce(function() {
// All the taxing stuff you do
}, 250);
window.addEventListener(‘resize’, myEfficientFn);

The function above will only fire once every quarter of a second instead of as quickly as it’s triggered; an incredible performance boost in some cases.

Use Cases:

  1. We can throttle a button click event if we do not want the user to spam by clicking the button frequently.
  2. In the case of the window resize event, if we want to redraw the UI only when the user has fixed the size of the window, we can use debouncing.
  3. With the Mouse move event, if we are displaying the location coordinates of the mouse pointer, it is much better to show the coordinates once the user reached the desired location. Here, we can use debouncing.

Summary:

In this article we talked about two design patterns: debounce and throttle.
We talked about why these patterns are so useful, and how they can improve the performance of our applications. We also saw common implementations of these patterns, whether in own our code or in external libraries. Finally, we saw some common, real-life usages, to better understand when to use debounce and when use throttle.

I recommend looking at the problem from the end-userʼs perspective (it may be a performance problem, a user-experience problem, or something else altogether) to understand which technique to use. Does the end-user need things to happen right away (hinting at the throttle)? Just once (hinting at debounce)? Or maybe every 250ms?

I hope some of you find this technique as useful as it’s been for me.

--

--

Yash Soni

Wanna be Javascript Developer, trying to share his knowledge!!