Debounce is delaying the execution of the function till the given time or in simpler words is that it makes sure that certain pieces of code will only get triggered once for the specified time frame.
The use cases of this sort of function are Search box suggestions, text-field auto-saves, and eliminating double-button clicks.
Hence it makes it a great question for an interview.
So Lets move ahead an implement one.
Let us create a boilerplate HTML code with an input tag where we can see this function in action,
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script defer src="index.js"></script>
</head>
<body>
<input type="text" name="debounce" id="debounce">
</body>
</html>
Now let's create a debounce function which we will be using on the input tag the sole purpose of which will be printing the value of input tag:
index.js
function debounce(fn, delay) {
let timer;
return (...args) => {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => fn.apply(this,args), delay);
}
}
function print(value) {
console.log(value);
}
const debounceInputChange = debounce(print, 1000);
let input = document.getElementById('debounce');
input.addEventListener('input', (e) => {
debounceInputChange(e.target.value);
});
Here we have created a function debounce which accepts two arguments a function fn which needs to be delayed(debounced) and a delay that determines the time frame for every function call.
Now the debounce function has two important parts a variable timer whose role is to check whether we have any function ready to be executed and we are returning an anonymus function forming a closure with the timer, fn, delay that handles all the logic.
The returning function accepts the arguments in the form of an array which basically can be used to invoke the fn function,
we check if the timer value is truthy value i.e there is a
timer already present we just remove it because a new set of values needs to be invoked and hence reinitialized it with a new timeout. Inside the timeout, we are calling the method fn with the args for the inner function.
In this example, print is the delayed/debounced function (which u guys can replace with any important function like API calls, etc.)
We now execute the debounce function and store it in debounceInputChange which is nothing but the internal function returned from the debounce, we will be just using this function for every input change made and passing the input value as an argument.
Thanks For Reading
Top comments (0)