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.

JavascriptResilience

Code

javascriptsnippet
28 lines
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-es is 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

FAQ

Which packages must be installed first?
Yes. The imports resolve to `lodash-es`, which the package manager must provide.