Debounce Implementation
Delay function execution until after a pause in calls.
Code
JavaScript
function debounce(fn, delay) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn.apply(this, args), delay);
};
}
const debouncedSearch = debounce((q) => console.log("Search:", q), 300);
debouncedSearch("a");
debouncedSearch("ab");
debouncedSearch("abc"); // Only this runs after 300msLine-by-line explanation
- 1.Store timeoutId to cancel previous pending calls.
- 2.clearTimeout cancels the previous timer.
- 3.setTimeout schedules the function after delay.
- 4.fn.apply(this, args) preserves context and passes arguments.
Expected output
Search: abc