Bind Method Explained - Debouncing, Improve Performance
Previous
57
/
57
Debouncing is a technique in JavaScript used to limit the number of function executions.
Simple definition:
- It delays function execution until a certain time has passed without any new event trigger.
Why do we need Debouncing?
Debouncing is mainly used to improve performance in cases like:
- Search boxes (API calls on typing)
- Auto-suggestions
- Input validation
- Resize / scroll events
Problem without debouncing:
- Every keypress triggers an API call
- Too many unnecessary API requests
- Slows down application performance
- Increases server load and cost
Real-life Analogy
Think of a child who keeps talking while you are working:
- You say: “Be silent for 10 seconds, then I will give chocolate”
- If the child speaks again → timer resets
- Only when child stays silent for full time → reward is given
Same concept applies in debouncing.
Without Debouncing (Problem Code)
function handleSearch() {
console.log("API Call Done");
}
<input type="text" onkeypress="handleSearch()">
Result:
- Every keypress → API call
- Inefficient and heavy
Debouncing Solution (Basic Version)
Step 1: Use setTimeout
let timer;
function handleSearch() {
clearTimeout(timer);
timer = setTimeout(() => {
console.log("API Call Done");
}, 1000);
}
How it works
- User types a key → timer starts
- If user types again → previous timer is cleared
- Only when user stops typing for 1 second → function executes
Final Reusable Debounce Function
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
Example Usage
function handleInput(event) {
console.log("Typing:", event.target.value);
}
const debouncedSearch = debounce(handleInput, 500);
<input type="text" onkeypress="debouncedSearch(event)">
Key Concepts Used
1. setTimeout
- Delays function execution
2. clearTimeout
- Cancels previous scheduled function
3. Closures
- Timer variable stays preserved between calls
4. apply(this, args)
- Keeps correct context and arguments
Final Working Flow
- User types input
- Function gets called
- Timer starts
- If user types again → previous timer cancels
- After user stops typing → API call executes