Home Courses Bind Method Explained - Debouncing, Improve Performance

Bind Method Explained - Debouncing, Improve Performance

57 / 57

Debouncing is a technique in JavaScript used to limit the number of function executions.

Simple definition:

  1. 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:

  1. Search boxes (API calls on typing)
  2. Auto-suggestions
  3. Input validation
  4. Resize / scroll events

Problem without debouncing:

  1. Every keypress triggers an API call
  2. Too many unnecessary API requests
  3. Slows down application performance
  4. Increases server load and cost


Real-life Analogy

Think of a child who keeps talking while you are working:

  1. You say: “Be silent for 10 seconds, then I will give chocolate”
  2. If the child speaks again → timer resets
  3. 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:

  1. Every keypress → API call
  2. 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

  1. User types a key → timer starts
  2. If user types again → previous timer is cleared
  3. 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

  1. Delays function execution

2. clearTimeout

  1. Cancels previous scheduled function

3. Closures

  1. Timer variable stays preserved between calls

4. apply(this, args)

  1. Keeps correct context and arguments


Final Working Flow

  1. User types input
  2. Function gets called
  3. Timer starts
  4. If user types again → previous timer cancels
  5. After user stops typing → API call executes


Share this lesson: