What Is Debouncing in JavaScript?
Debounce delays execution until activity stops. Here is the implementation and use cases.
What Is Debouncing in JavaScript?
Debouncing delays the execution of a function until the user stops calling it for a specified delay. It is asked by Flipkart and many other companies.
Implementation
function debounce(fn, delay) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); }; }
How It Works
- Each call clears the previous timer.
- A new timer is set.
- Only the last call within the delay period executes.
Use Case: Search Input
const search = debounce((query) => { fetchResults(query); }, 300); input.addEventListener("input", (e) => search(e.target.value));
Without debounce, typing "hello" makes 5 API calls. With debounce (300ms), only 1 call is made after the user stops typing.
Use Cases
- Search inputs (delay API call until typing stops).
- Window resize (delay layout recalculation).
- Form validation (validate after user stops editing).
- Auto-save (save after user stops changing).
The Takeaway
Debounce: clear the previous timer on each call, set a new timer. Only the last call within the delay period executes. Use 300ms for search inputs. Closures (timer variable) make it work. Asked by Flipkart.
A technique that delays function execution until the user stops calling it for a specified delay. Each call clears the previous timer and sets a new one. Only the last call executes.
function debounce(fn, delay) { let timer; return function(...args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); }; }
To avoid making an API call on every keystroke. Without debounce, typing 'hello' makes 5 calls. With debounce (300ms), only 1 call is made after the user stops typing.
300ms is a good default for search inputs. 200ms for faster response, 500ms for slower. Adjust based on the use case and API speed.
Yes. The timer variable is in the outer function's scope. The returned function closes over it. Each call clears and resets the same timer via the closure.
Ready to master React completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.
Master React
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

