Implement Debounce with Leading and Trailing Options
Learn how to create a custom debounce function that fires both on the leading and trailing edge — ideal for responsive search inputs.
intermediatePerformance optimizationjavascriptdebounceperformanceeventsoptimization
Published: 11/12/2025
Updated: 11/12/2025
Advertisement
Question
Implement a debounce function that:
- Fires instantly on the first input (leading edge)
- Also fires after typing stops (trailing edge)
Implementation
function debounce(fn, delay, options = { leading: false, trailing: true }) {
let timer;
return function (...args) {
const callNow = options.leading && !timer;
clearTimeout(timer);
timer = setTimeout(() => {
if (options.trailing) fn.apply(this, args);
timer = null;
}, delay);
if (callNow) fn.apply(this, args);
};
}
Usage Example:
const searchHandler = debounce(fetchResults, 300, {
leading: true,
trailing: true,
});
input.addEventListener('input', searchHandler);
Visualization
graph TD A[User Typing] --> B[Leading Edge Fire] B -->|Pause| C[Trailing Edge Fire After Delay]
Summary
- Leading edge → triggers instantly
- Trailing edge → triggers after idle
- Great for real-time searches, auto-saves, and resize events
- Combine both for best UX and performance
Related Videos
Watch these videos to learn more about this topic
Frequently Asked Questions
When should you use leading debounce?
When you want the first event to trigger immediately, e.g. instant feedback search.
Advertisement
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.
Advertisement