Lodash Debounce and Throttle for UI Events
Tame high-frequency DOM and scroll events with Lodash debounce and throttle, including leading and trailing edge control and cancelable handles.
Code
import { debounce, throttle } from 'lodash-es';
const saveDraft = debounce(
(content) => {
console.log('autosaving draft of', content.length, 'chars');
},
800,
{ leading: false, trailing: true, maxWait: 3000 },
);
saveDraft('first edit');
saveDraft('second edit');
saveDraft('third edit');
const onScroll = throttle(
() => console.log('scroll checkpoint at', window.scrollY),
200,
{ leading: true, trailing: false },
);
document.addEventListener('scroll', onScroll, { passive: true });
window.addEventListener('beforeunload', () => {
saveDraft.cancel();
onScroll.cancel();
});
saveDraft.flush();What the code does
The snippet’s external surface is debounce, throttle, all of it via lodash-es.
Top-level bindings saveDraft, onScroll hold the demo state — nothing sits inside a function scope.
What to watch for
- Plan for an install step:
lodash-esis a real dependency, resolved by the package manager. - The snippet leans on
document,window— browser-only surfaces a bare Node process cannot provide.
Using it
Output lines are prefixed (autosaving draft of, scroll checkpoint at), making each step’s effect easy to spot.
Key statements
window.addEventListener('beforeunload', () => {
saveDraft.cancel();
onScroll.cancel();
});
document.addEventListener('scroll', onScroll, { passive: true });
(content) => {
console.log('autosaving draft of', content.length, 'chars');
},
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Which packages must be installed first?
- Yes. The imports resolve to `lodash-es`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.