Debounce Async With Cancel Token

Debounce async function calls with cancel tokens and pending state tracking for UI input handling.

TypescriptResilience

Code

typescriptsnippet
1 line
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};}

Inside the snippet

Debounce Async With Cancel Token is built around the function debounced.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

The result is a fresh construction, so callers can keep their originals.

Putting it to use

debounceAsync is what another module would consume; nothing else here is load-bearing for callers.

Interactive Tools for This Topic

FAQ

Does `debounceAsync` modify its input?
The input survives unchanged; what you get back is a newly constructed value.
Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. The file defines `debounced` at load time.