Debouncing & Throttling
The article will give explain the concept of Debouncing vs Throttling with real-world examples.
Throttling and debouncing are used to improve the performance of the application
Debouncing: Delay between most frequent execution.
Throttling: Limit the rate at which an execution takes place
I understand the above simple definition is a little bit difficult to understand. We will take a real-world example with code to better understand the concept.
Consider you are searching on an E-commerce website. It will give some suggestions for each letter we type ( change in the input field) it will call API to get some suggestions most frequently. We can somehow decrease the number of APIs it is making using a technique called debouncing.
Usually, we type in the input field continuously. In between or after typing we give some delay (like half a second) to think or to click the search icon. So we can make an API whenever a User gives some delay (mostly 100ms) thus decreasing the API request count. Run the below code with function handleDelay and directly calling callAPI you can notice the change
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Debouncing</title>
</head>
<body>
<input type="text" oninput="handleDelay(event)" / >
<script>
function callAPI(e) {
console.log(e.target.value);
}
function handleDelay(e) {
let timer;
// Clearing Previous timer
clearTimeout(timer);
// Creating a timer
timer = setTimeout(() => {
callAPI(e);
}, 100);
}
</script>
</body>
</html>
Consider pressing the refresh button ten times within a minute or clicking a button to call an API or submit to an API. This can generate too many requests within a short time. To limit this, a technique called throttling can be employed. This involves rate-limiting the execution, such as calling the API once every 5 seconds or refreshing once every 2 seconds when pressed repeatedly
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Throttling</title>
</head>
<body>
<button onclick="throttle()">Refresh</button>
<script>
function Refresh(e) {
console.log("Refreshed");
}
const throttle = DelayRefresh();
function DelayRefresh(e) {
let timer;
return function () {
// Creating a time if not present
if (!timer) {
Refresh();
timer = setTimeout(() => {
// Remove after 2 seconds
timer = null;
}, 2000);
}
};
}
r
</script>
</body>
</html>
Hope you understand debouncing and throttling. Like and share with your friends. I will meet you in next blog.