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;}Report a problem with this exampleOpens a pre-filled issue on GitHub.