Community JavaScript Snippet

Debounce With Leading + Trailing Edges and a cancel() Method

The trailing-only debounce in every tutorial works for search inputs and breaks on click handlers. Here is the lodash-style version with leading edge, cancel(), and flush(), in 30 lines.

Debounce With Leading + Trailing Edges and a cancel() Method

The trailing-only debounce in every tutorial works for search inputs and breaks on click handlers. Here is the lodash-style version with leading edge, cancel(), and flush(), in 30 lines.

JavaScript
Frontend
3 snippets
throttling
performance
code-template
hiroshiward

By @hiroshiward

December 18, 2025

·

Updated May 18, 2026

915 views

13

4.4 (8)

The four behaviors compose naturally on top of one timer reference. Leading is if (leading && timer === null), trailing is the contents of the timeout callback, cancel clears the timer and forgets the queued args, and flush clears the timer but invokes anyway with the queued args. The most common bug I have shipped in this code is forgetting to capture this and args together: a debounced method on a class instance must keep both for the fn.apply(ctx, args) call inside invoke, or you lose the this binding silently. The result-caching is a small lodash-compat detail that lets you read the previous return value off a debounced getter; few callers use it but its absence is surprising.