Debouncing and throttling in JavaScript

Rajan Lagah
2 min readDec 7, 2023

--

Debouncing

When you have to run some heavy function like API call and you want to optimize that function calls. A classic example will be when you search for a product on Amazon or Flipkart it shows you the product suggestions in autofill select dropdown based on value you have entered.

As in the above example, I have typed the word `apple` which is 5 keystrokes. And we don't want to fire suggestion API 5 times.

As we can see amazon is making api call 3 + 1 ( 1 is when you click on it ).

This we can achieve by debouncing.

It will wait for some time after the last keystroke and then run the API function.

const functionDelay = 500 // ms
let apiCount = 0
const apiExample = function () {
console.log("API CALLED", ++apiCount)
}
function debouncing(fn, delay) {
let timer
return function () {
clearTimeout(timer)
timer = setTimeout(function () {
fn.apply(this,args)
}, delay)
}
}
const betterApiCall = debouncing(apiExample, functionDelay)

The above code is how we can create a debouncing function. We will run betterApiCall the function on input change.

The logic for debouncing is to create a timeout function that will run the given function and clear the older generated timeout.

Throttling

Unlike debouncing, which waits for a pause in the events, throttling ensures that a function is executed at a regular interval, limiting the number of times it can be called within a specified period.

function throttle(func, delay) {
let isThrottled = false;

return function() {
if (!isThrottled) {
func.apply(this, arguments);
isThrottled = true;

setTimeout(() => {
isThrottled = false;
}, delay);
}
};
}
function handleCall() {
console.log('Call!');
// Your action here
}
const throttledClick = throttle(handleCall, 1000);
throttledClick()
throttledClick()
throttledClick()

Here you will see console will print Call! only once.

Throttling can be used in places where we want to keep running functions irrespective of the last input. Like Auto Saving let’s say you have written 100 words non-stop and then the tab is closed now if implement debouncing and wait for your last keystroke then those 100 words will be lost. But on the other hand as the medium does it will call save API after ‘x’ seconds so minimum data is lost.

So this is all about Debouncing and Throttling. I hope you have learned something new today.

--

--