Performance and UX on the client side can hinge on how you handle frequent events like scroll, resize, or input. Two tiny but mighty tools—throttle and debounce—can dramatically improve responsiveness and reduce backend load.
Debounce: Waits for a pause in activity, then fires the last event.
Throttle: Limits how often a function can run, e.g., once every 200ms.
The article provides robust, cancelable versions of both:
debounce(fn, wait, immediate) with .cancel() and .flush()
throttle(fn, wait, { leading, trailing }) with .cancel()
Debounce: Search input, auto-save, resize end
Throttle: Scroll events, mouse movement, analytics
requestAnimationFrame Throttle: For buttery-smooth animations
useDebouncedValue: Debounced state updates
useThrottleCallback: Stable throttled handlers
Debounced fetch with AbortController to cancel stale requests
Use fake timers (e.g., Jest)
Assert .cancel() and .flush() behaviors
Be mindful of async quirks and SSR limitations
Throttle is for client-side pacing. Server-side rate limiting is for protection. They complement each other.
Debounce reduces noise; throttle caps frequency.
Use requestAnimationFrame for visual work.
Prefer Lodash if you want battle-tested utilities.
0
8
1