Debounce With Leading And Trailing Edge

Implement debounce firing on leading edge then trailing edge with cancel and flush for async event streams.

JavascriptResilience

Code

javascriptsnippet
1 line
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

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. The file defines `debounce`, `d` at load time.