Debounce Async With Cancel Token
Debounce async function calls with cancel tokens and pending state tracking for UI input handling.
Code
export function debounceAsync<T extends(...args:any[])=>Promise<any>>(fn:T,wait:number){let timer:NodeJS.Timeout|null=null;let pending=false;async function debounced(...args:Parameters<T>):Promise<ReturnType<T>|undefined>{pending=true;return new Promise((resolve)=>{if(timer)clearTimeout(timer);timer=setTimeout(async()=>{pending=false;resolve(await fn(...args));},wait);});}debounced.cancel=()=>{if(timer)clearTimeout(timer);timer=null;pending=false;};debounced.isPending=()=>pending;return debounced as typeof debounced&{cancel:()=>void;isPending:()=>boolean};}Report a problem with this exampleOpens a pre-filled issue on GitHub.