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();Report a problem with this exampleOpens a pre-filled issue on GitHub.