While building an app using JavaScript. We may need to call the function many times to achieve the desired result.
Some examples are
- While scrolling or resizing the screen you would want to compute something.
- Sometime we may need to display quick results as user types in the input field.
Let's see, how we usually write code to achieve the desired result.
<!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 class="search" type="text" placeholder="search"/>
<script src="index.js"></script>
</body>
</html>
let count = 0;
function search(query){
// some api call
console.log("result",count++)
}
document.querySelector(".search").addEventListener("input",(e)=>{
search(e.target.value);
})
In the above example, If I search for a laptop, The function search will be called 6 times. Which is an inefficient way of calling a function. And it is very expensive for JavaScript.
You must be wondering what do you mean by expensive for JavaScript?
JavaScript is a synchronous single-threaded language. Which means we have a single callstack to execute everything. And because it is single-threaded, we should not block the thread by calling functions unnecessary.
But wait ...
How do we prevent unnecessary function calls to improve performance?
Here, the concept of debouncing kicks into the picture.
Debouncing is a technique used to improve the browser's performance. It ensures that time-consuming tasks do not fire so often, In other words, it limits the rate at which a function gets invoked.
Let's re-write the above code using Debouncing technique.
let count = 0;
function search(query){
// some api call
console.log("result",count++)
}
const magicFunction = debounce(search,300);
function debounce(func, delay){
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
func(...args);
}, delay);
};
}
document.querySelector(".search").addEventListener("input",(e)=>{
magicFunction(e.target.value);
});
The idea behind debouncing technique is that we do not call function during the event but after the event.
In the above example, We can clearly see.
debounce is a higher order function(HOF). Which takes two parameters the first parameter will be a function and the second will be a delay.
If the delay between two keystrokes is less than 300ms, function will not execute and setTimeout
will be destroyed. And if the delay is more than 300ms, then only function will execute.
That's how we can implement the debouncing technique to improve our app's performance
follow me for more such blog posts.
Let me know if this blog was helpful.
Top comments (0)