Debounce With Leading And Trailing Edge
Implement debounce firing on leading edge then trailing edge with cancel and flush for async event streams.
Code
export function debounce(fn,wait,{leading=false,trailing=true}={}){let t=null,last=null,inv=false;function d(...a){last=a;if(leading&&!inv){fn.apply(this,a);inv=true;}if(t)clearTimeout(t);t=setTimeout(()=>{if(trailing&&(!leading||last!==null))fn.apply(this,last);t=null;inv=false;last=null;},wait);}d.cancel=()=>{if(t)clearTimeout(t);t=null;inv=false;last=null;};d.flush=()=>{if(t){clearTimeout(t);fn.apply(this,last);t=null;}};return d;}Inside the snippet
Count the functions debounce and d as the entire surface area of Debounce With Leading And Trailing Edge.
Using it
Entry signature: export function debounce(fn,wait,{leading=false,trailing=true}={})
Treat debounce as the API: import it, and ignore the supporting code.
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
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. The file defines `debounce`, `d` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.