Write a debounce with leading and trailing options
Write a debounce with leading and trailing options in JavaScript, so a call can fire at the start, the end of the burst, or both. Node.js 24.
Plain debounce waits until calls stop. Sometimes you want the first call right away, such as a save button that reacts at once and ignores repeats.
const debounce = (fn, wait, { leading = false, trailing = true } = {}) => {
let timer;
let pending;
return (...args) => {
const startOfBurst = timer === undefined;
pending = args;
clearTimeout(timer);
if (startOfBurst && leading) fn(...args), (pending = null);
timer = setTimeout(() => {
timer = undefined;
if (trailing && pending) fn(...pending);
pending = null;
}, wait);
};
};
const log = debounce((x) => console.log('call', x), 20, { leading: true });
log(1); log(2); log(3);call 1
call 3The first call starts a burst and fires at once. The later calls reset the timer and store the latest arguments. When 20 ms pass without a call, the trailing edge fires with 3. With leading: true and trailing: false only call 1 is printed.
When the burst has only one call and leading is on, it fires immediately and the trailing call is skipped, because pending was cleared. Utility libraries implement the same options with more edge cases.