debounce and throttle in js
Debounce in JavaScript
Controlling High-Frequency Function Calls
Imagine you're building a search box for an e-commerce website.
A user wants to search for a product called "JavaScript Course".
As they type, the input generates several events:
J
Ja
Jav
Java
JavaS
JavaSc
JavaScr
JavaScrip
JavaScript
If we call the search API after every keystroke, we might send nine separate requests for a single search.
That's unnecessary work.
The user hasn't even finished typing, but our application is already making requests.
Wouldn't it be better if we waited until the user stopped typing and then made just one API request?
This is exactly the problem Debouncing solves.
1. The Story & Real-World Analogy
The Smart Hotel Elevator
Imagine a hotel elevator equipped with an automatic door sensor.
The elevator waits for five seconds before closing its doors.
A guest enters, and the five-second timer starts.
Two seconds later, another guest enters. The timer resets to five seconds.
Three seconds later, a third guest enters. The timer resets again.
The elevator doors close only when nobody has entered for five continuous seconds.
The elevator doesn't start moving after every guest. It waits until the activity stops.
Debouncing works in exactly the same way.
Whenever a function is called, we start a timer. If another call happens before the timer expires, we cancel the previous timer and start a new one.
Only when the specified period passes without another call does the function actually execute.
In JavaScript, this is useful for events that can fire very frequently, such as:
Search input
Window resizing
Form validation
Autosaving drafts
Filtering large datasets
What is Debouncing?
Debouncing is a technique that delays the execution of a function until a specified amount of time has passed without another invocation.
In simpler words:
Wait until the user stops performing an action, then execute the function once.
2. Understanding How Debounce Works
Before writing the implementation, let's understand what needs to happen internally.
Suppose we have a function that should execute only after 500 milliseconds of inactivity.
function search() {
console.log("Searching...");
}
We want to control when this function executes.
A debounce function needs to perform three important operations.
Step 1: Maintain a Timer
We need a variable that remembers the currently scheduled timer.
let timerId;
This variable stores the ID returned by setTimeout().
Why do we need it?
Because if another call happens before the timer expires, we need to cancel the previous timer.
Step 2: Cancel the Previous Timer
Whenever the debounced function is called, we clear the previous timer.
clearTimeout(timerId);
This prevents the previously scheduled execution from happening.
Step 3: Schedule a New Timer
After clearing the previous timer, we schedule a new one.
timerId = setTimeout(() => {
search();
}, 500);
If no new call happens within 500 milliseconds, the callback executes.
But if another call happens before that time, the timer gets cleared and a new one starts.
This is the entire foundation of debouncing.

3. Building Our First Debounce Function
Let's combine the three steps into a simple implementation.
function debounce(fn, delay) {
let timerId;
return function () {
clearTimeout(timerId);
timerId = setTimeout(() => {
fn();
}, delay);
};
}
Let's understand what we're doing.
debounce()receives a function and a delay.It creates a
timerIdvariable.It returns another function.
Whenever the returned function is called, the previous timer is cleared.
A new timer is scheduled.
If no additional call happens before the delay expires, the original function executes.
Let's use it:
function search() {
console.log("Searching...");
}
const debouncedSearch = debounce(search, 500);
debouncedSearch();
debouncedSearch();
debouncedSearch();
Even though we called debouncedSearch() three times, the original search() function executes only once, after 500 milliseconds of inactivity.
But how does timerId remember its value?
Look at this line:
let timerId;
It's declared inside debounce(), but the returned function continues to access it even after debounce() has finished executing.
Why?
Because of closures.
The returned function remembers the lexical environment in which it was created.
That means timerId remains available between calls.
For example:
const debouncedSearch = debounce(search, 500);
debouncedSearch(); // Creates Timer 1
debouncedSearch(); // Clears Timer 1 and creates Timer 2
debouncedSearch(); // Clears Timer 2 and creates Timer 3
All three calls share the same timerId variable because they use the same returned function and its closure.
This is why closures are essential to the debounce implementation.
4. Preserving Arguments and the this Context
Our first implementation works, but it has a limitation.
What if the original function expects arguments?
Consider:
function searchProduct(query) {
console.log("Searching for:", query);
}
We want to debounce it:
const debouncedSearch = debounce(searchProduct, 500);
debouncedSearch("JavaScript");
But our current implementation calls:
fn();
We aren't passing the original arguments.
We also need to preserve the this context because the original function might be an object method.
Let's improve our implementation.
function debounce(fn, delay) {
let timerId;
return function (...args) {
const context = this;
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(context, args);
}, delay);
};
}
Now let's understand the important parts.
Rest Parameters
function (...args)
The rest parameter collects all arguments passed to the debounced function into an array.
For example:
debouncedSearch("JavaScript", "Programming");
The arguments become:
args = ["JavaScript", "Programming"];
Preserving this
const context = this;
We save the current calling context before scheduling the timer.
Using apply()
fn.apply(context, args);
apply() calls the original function with:
The original
thisvalue.The original arguments.
This ensures that our debounce wrapper doesn't accidentally change how the original function behaves.
5. Production-Ready Debounce with Cancel Support
Sometimes we don't want the pending function to execute anymore.
Imagine a user starts typing in a search box but then navigates away from the page.
We may want to cancel the scheduled search.
We can support this by adding a .cancel() method.
function debounce(fn, delay = 300) {
let timerId = null;
const debounced = function (...args) {
const context = this;
if (timerId !== null) {
clearTimeout(timerId);
}
timerId = setTimeout(() => {
timerId = null;
fn.apply(context, args);
}, delay);
};
debounced.cancel = function () {
if (timerId !== null) {
clearTimeout(timerId);
timerId = null;
}
};
return debounced;
}
Let's understand what changed.
First:
let timerId = null;
We use null to indicate that no timer is currently pending.
Second:
timerId = null;
When the timer executes, we reset the variable because there is no longer a pending timer.
Third:
debounced.cancel = function () {
if (timerId !== null) {
clearTimeout(timerId);
timerId = null;
}
};
We attach a cancel() method to the returned function.
Now we can cancel a pending execution whenever needed.
Practical usage: Search Autocomplete
const searchApi = (query) => {
console.log("Searching database for:", query);
};
const handleSearch = debounce(searchApi, 200);
// Simulating rapid typing
handleSearch("r");
handleSearch("re");
handleSearch("rea");
handleSearch("react");
// Cancel the pending execution if needed
// handleSearch.cancel();
Output after 200 milliseconds of inactivity:
Searching database for: react
Only the final call executes because each new call resets the timer.
Important: Debouncing controls when a function starts. It does not automatically cancel an API request that has already started.
6. Leading Edge vs Trailing Edge Debouncing
So far, our implementation has followed one behavior: it executes the function after the user stops triggering events.
This is called trailing-edge debounce.
But there is another option.
Trailing Edge
The function executes after the specified period of inactivity.
Example:
Call → Call → Call → Silence → Execute
This is the standard debounce behavior we've implemented so far.
It's commonly used for:
Search suggestions
Form validation
Autosaving
Filtering
Leading Edge
The function executes immediately when the first call happens.
Subsequent calls during the waiting period don't trigger another execution.
Example:
Call → Execute → Call → Call → Silence
This can be useful when an action should happen immediately but repeated rapid actions should be suppressed.
Understanding the difference
Trailing Edge | Leading Edge |
|---|---|
Executes after inactivity | Executes immediately on the first call |
Waits for the final call in a burst | Ignores subsequent calls during the cooldown period |
Useful for search input | Useful for immediate actions that should not repeat rapidly |
Leading and trailing behavior can also be combined in more advanced debounce implementations.
For this chapter, our main implementation uses trailing-edge debounce.
7. Debouncing in React
Debouncing is especially useful in React applications, particularly for search inputs.
But there's an important mistake developers commonly make.
Consider:
function Search() {
const handleSearch = debounce((value) => {
console.log("Searching:", value);
}, 500);
return (
<input => handleSearch(event.target.value)}
/>
);
}
What's wrong here?
Every time React renders the component, it creates a new debounced function.
Each new function has its own closure and its own timer.
This defeats the purpose of debouncing because calls across renders don't share the same timer.
Solution: useMemo()
We can use useMemo() to create the debounced function once and preserve it between renders.
import { useEffect, useMemo } from "react";
function Search() {
const debouncedSearch = useMemo(
() =>
debounce((value) => {
console.log("Searching:", value);
}, 500),
[]
);
useEffect(() => {
return () => {
debouncedSearch.cancel();
};
}, [debouncedSearch]);
return (
<input => {
debouncedSearch(event.target.value);
}}
/>
);
}
Now:
useMemo()preserves the debounced function between renders.Multiple input events use the same timer.
The timer resets whenever the user types again.
The cleanup function cancels a pending timer when the component unmounts.
An important React detail
The empty dependency array is suitable here because the example's callback doesn't depend on changing props or state.
In a real application, if the debounced callback uses changing values from the component, make sure those dependencies are handled correctly. Otherwise, the callback may use stale values.
Also, if the debounce function itself is recreated due to changing dependencies, the old pending timer should be cleaned up.
8. Debounce vs Throttle
Debounce and throttle are both techniques for controlling high-frequency function calls.
They solve related problems, but their behavior is different.
Let's understand the difference.
Debounce
Debounce waits until activity stops for a specified duration before executing the function.
Example: A user types quickly into a search box. We want to search only after they stop typing.
Throttle
Throttle limits how frequently a function can execute.
For example, if we allow a function to execute at most once every 1000 milliseconds, repeated calls during that interval are ignored or deferred depending on the throttle implementation.
Example: A user scrolls a page. We may want to update a scroll-related calculation at controlled intervals rather than on every scroll event.
Visual comparison

Debounce | Throttle |
|---|---|
Waits for inactivity | Limits execution frequency |
Usually executes once after a burst ends | Can execute repeatedly during continuous activity |
Useful for search input | Useful for scroll and resize handling |
Resets its timer on every call | Uses a time interval to control execution |
Remember: Debounce waits for stillness; throttle controls frequency.
We'll explore throttle and its implementation separately.
9. Common Pitfalls and Interview Traps
Let's review some common mistakes.
Mistake 1: Recreating the Debounced Function
function Search() {
const debouncedSearch = debounce(searchApi, 500);
}
If this code runs on every React render, a new debounce function and timer closure are created.
Solution: Preserve the debounced function using useMemo() or another stable lifecycle strategy.
Mistake 2: Not Preserving Arguments
return function () {
setTimeout(() => {
fn();
}, delay);
};
This loses the arguments passed to the original function.
Solution:
return function (...args) {
setTimeout(() => {
fn.apply(this, args);
}, delay);
};
For a timer callback, save this before scheduling it, rather than relying on the timer callback's own this.
Mistake 3: Not Clearing the Previous Timer
If we don't clear the previous timer, every call schedules a separate execution.
That defeats the purpose of debouncing.
Solution:
clearTimeout(timerId);
Mistake 4: Forgetting Cleanup in React
If a component unmounts while a debounce timer is pending, the callback can still execute.
Solution:
useEffect(() => {
return () => {
debouncedSearch.cancel();
};
}, [debouncedSearch]);
Mistake 5: Thinking Debounce Cancels an API Request
Debounce prevents a scheduled function from executing until the delay expires.
Once an API request has started, clearing the debounce timer cannot cancel that request.
If we also need to cancel an in-flight request, we can use AbortController where the API supports it.
10. Interview Coding Questions
Now let's solve some practical interview problems.
Question 1: Button Press Counter with Debounce
Problem:
Create a button UI with two counters:
Button Pressed: Increase every time the user clicks the button.Triggered: Increase only after the user stops clicking for 800 milliseconds.
For example, if the user clicks five times quickly, the first counter should show 5, but the second counter should increase only once.
HTML:
<button class="increment_btn">Click Me</button>
<p>
Button Pressed:
<span class="increment_pressed">0</span>
</p>
<p>
Triggered:
<span class="increment_count">0</span>
</p>
JavaScript:
const btn = document.querySelector(".increment_btn");
const btnPress = document.querySelector(".increment_pressed");
const count = document.querySelector(".increment_count");
let triggerCount = 0;
let pressedCount = 0;
const debouncedCount = debounce(() => {
triggerCount += 1;
count.textContent = triggerCount;
}, 800);
btn.addEventListener("click", () => {
pressedCount += 1;
btnPress.textContent = pressedCount;
debouncedCount();
});
Expected behavior:
If the user clicks five times within a short period:
Button Pressed: 5
Triggered: 1
The pressedCount changes immediately, while triggerCount changes only after 800 milliseconds of inactivity.
Question 2: Implement Debounce from Scratch
Problem:
Implement your own debounce function without using Lodash or any external library.
Requirements:
Accept a callback and delay.
Clear the previous timer.
Execute only after the delay has passed without another call.
Preserve the original arguments and
thiscontext.
Solution:
function myDebounce(callback, delay) {
let timerId;
return function (...args) {
const context = this;
clearTimeout(timerId);
timerId = setTimeout(() => {
callback.apply(context, args);
}, delay);
};
}
Usage:
function searchProduct(query) {
console.log("Searching for:", query);
}
const debouncedSearch = myDebounce(searchProduct, 500);
debouncedSearch("JavaScript");
debouncedSearch("React");
debouncedSearch("Node.js");
Output after 500 milliseconds of inactivity:
Searching for: Node.js
Only the last call executes.
Question 3: Implement Throttle from Scratch
Problem:
Implement a throttle function that allows a callback to execute at most once during a specified interval.
Requirements:
Accept a callback and delay.
Track the time of the previous execution.
Ignore calls that happen before the interval expires.
Preserve arguments and
this.
Solution:
function myThrottle(callback, delay) {
let lastExecution = 0;
return function (...args) {
const now = Date.now();
if (now - lastExecution < delay) {
return;
}
lastExecution = now;
return callback.apply(this, args);
};
}
Usage:
const throttledFunction = myThrottle(() => {
console.log("Function executed");
}, 1000);
window.addEventListener("scroll", throttledFunction);
This is a leading-edge throttle: it executes immediately when the interval allows and ignores calls during the remaining interval.
Question 4: Button Press Counter with Throttle
Problem:
Create a button UI with two counters:
Button Pressed: Increase every time the user clicks.Triggered: Increase at most once every 1000 milliseconds.
HTML:
<button class="increment_btn">Click Me</button>
<p>
Button Pressed:
<span class="increment_pressed">0</span>
</p>
<p>
Triggered:
<span class="increment_count">0</span>
</p>
JavaScript:
const btn = document.querySelector(".increment_btn");
const btnPress = document.querySelector(".increment_pressed");
const count = document.querySelector(".increment_count");
let triggerCount = 0;
let pressedCount = 0;
const throttledCount = myThrottle(() => {
triggerCount += 1;
count.textContent = triggerCount;
}, 1000);
btn.addEventListener("click", () => {
pressedCount += 1;
btnPress.textContent = pressedCount;
throttledCount();
});
Expected behavior:
If the user clicks ten times within one second:
Button Pressed: 10
Triggered: 1
If the user continues clicking after the interval expires, another execution can happen.
11. Quick Revision Cheat Sheet
Concept | Explanation |
|---|---|
Debounce | Delays execution until a period of inactivity |
| Schedules the function execution |
| Cancels the previously scheduled timer |
Closure | Keeps the timer ID available between calls |
| Preserves the original function's context and arguments |
Trailing edge | Executes after the activity stops |
Leading edge | Executes immediately on the first call |
| Cancels a pending debounced execution |
Throttle | Limits how frequently a function executes |
The most important things to remember
Debounce reduces unnecessary function executions during rapid events.
Every new call resets the timer.
The callback executes after the specified period of inactivity.
Closures preserve the timer ID between calls.
Preserve
thisand arguments when wrapping functions.Provide cancellation support when pending executions need cleanup.
Use debounce for search input, autosaving, and validation.
Use throttle when you want to limit execution frequency.
What's Next?
We now understand how to control high-frequency function calls using debouncing.
But there is another technique that solves a similar problem in a different way.
Instead of waiting until the user stops performing an action, what if we want our function to execute at controlled intervals while the action is still happening?
Imagine a user continuously scrolling a page. We don't want to wait until scrolling stops before updating everything. We want to perform certain calculations periodically.
That's where Throttling in JavaScript comes in.
In the next chapter, we'll understand how throttle works, implement it from scratch, and compare it with debounce through practical examples.