JavaScript › Functional Programming
How do you implement a debounce function using closures, and how is it a functional programming technique?
AdvancedAnswer
debounce() returns a new function that wraps a closure over a timer variable, delaying the original function's execution until a pause in calls occurs — it's a higher-order function that takes a function and returns an enhanced function, a core FP pattern.
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
const debouncedSearch = debounce(runSearch, 300);Real-world example Delaying an API search request until the user stops typing for 300ms, instead of firing on every keystroke.