Advertisement
Advanced JavaScript, Functional Programming

How do you implement a debounce function using closures, and how is it a functional programming technique?

Short answer

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.

Save JavaScript mock interview
Advertisement
AModel answer
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.
Likely follow-ups
  • How does debounce differ from throttle, and when would you choose each?
Related topics