Understanding Throttling and Debouncing in JavaScript
When working with JavaScript, events like typing, clicking, and scrolling can happen many times in a short period. If we run a function every time an event occurs, it can cause performance issues.
To solve this, we use two important techniques: throttling and debouncing.
Throttling
What is Throttling?
A function is allowed to run only once in a fixed time interval, even if the event happens many times.
Why use Throttling?
We use throttling to improve performance and avoid too many function calls.
Without throttling:
- Too many API calls
- High CPU usage
- Poor user experience
With throttling:
- Function runs at controlled intervals
- Reduces CPU usage
- Improves user experience
Where to use Throttling?
Throttling helps to prevent:
- Multiple rapid clicks
- Duplicate form submissions
Example idea:
Instead of running a function 100 times per second, run it only once every 1 second.
Example: Throttling Click Counter
<button id="throttledBtn">Click Me</button>
<h2 id="throttledCounter">0</h2>
<script>
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => {
inThrottle = false;
}, limit);
}
}
}
let count = 0;
const throttledIncrement = throttle(() => {
count++;
document.getElementById('throttledCounter').textContent = count;
}, 1000);
document.getElementById('throttledBtn')
.addEventListener('click', throttledIncrement);
</script>
Explanation
Even if the user clicks many times quickly, the counter increases only once per second. This controls how often the function runs.
Debouncing
What is Debouncing?
A function runs only after a certain delay, and only when the event stops happening.
If the user keeps typing, the function will not run. When the user stops typing, it runs once.
Why use Debouncing?
We use debouncing to avoid unnecessary repeated function calls.
Without debouncing:
- Every key press triggers API call
- Too many requests
- Slow performance
With debouncing:
- Only final action triggers function
- Reduces API calls
- Improves performance
Where to use Debouncing?
- Search bars
- Auto-suggestions
- API calls after user stops typing
Example: Debounced Search Input
<input type="text" id="search" placeholder="Type to search..." />
<script>
function debouncing(func, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => func(...args), delay);
};
}
function callApi(event) {
const query = event.target.value;
console.log("API Call:", query);
fetch(`https://jsonplaceholder.typicode.com/posts?q=${query}`)
.then(res => res.json())
.then(data => console.log(data));
}
const betterFn = debouncing(callApi, 500);
document.getElementById('search')
.addEventListener('keyup', betterFn);
</script>
Explanation
When the user types, the timer keeps resetting. The function runs only after the user stops typing for 500 milliseconds. This avoids multiple API calls.
Difference Between Throttling and Debouncing
Throttling runs a function at fixed intervals during continuous actions.
Debouncing runs a function only after the action has stopped.
Throttling is useful when we need continuous updates with limits.
Debouncing is useful when we only care about the final result.
Top comments (0)