Explain debounce vs throttle vs memoize
Interviewers ask when to use debounce, throttle, and memoization, and how they differ in behavior. Explain each with practical frontend examples.
Asked at DriveNets
Answer
// Debounce: run after user stops triggering events for delay ms. // Best for: search input, autosave, expensive validation. // Behavior: many rapid calls -> one final call.
// Throttle: run at most once per interval. // Best for: scroll, resize, drag pointer updates. // Behavior: many rapid calls -> periodic calls.
// Memoize: cache function outputs for identical inputs. // Best for: pure expensive computations. // Behavior: repeated same args -> instant cached result.
// Interview framing: // - Debounce controls "when" execution happens (after quiet time). // - Throttle controls "how often" execution can happen. // - Memoize controls "whether recomputation is needed".
// Usage examples: const onSearch = debounce((q) => api.search(q), 300) input.addEventListener('input', (e) => onSearch(e.target.value))
const onScroll = throttle(() => updateVisibleRows(), 100) window.addEventListener('scroll', onScroll)
const fib = memoize((n) => (n < 2 ? n : fib(n - 1) + fib(n - 2))) fib(40) // first call expensive fib(40) // cached // // Common interviewer follow-ups: // Q: Leading/trailing behavior for debounce/throttle? // A: Debounce is usually trailing by default; throttle is often leading with optional trailing. // Q: How to cancel pending debounce/throttle calls? // A: Expose cancel() to clear timers and optionally flush() to run pending work immediately. // Q: Memoization pitfalls? // A: Non-serializable args break naive keying, and unbounded caches can leak memory.
Source: Glassdoor — DriveNets Front End Developer: https://www.glassdoor.com/Interview/DriveNets-Front-End-Developer-Interview-Questions-EI_IE2183997.0,9_KO10,29.htm