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};}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
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.LLM Token & Cost EstimatorEstimate BPE-approximate LLM token counts across English, CJK text, and source code and compare request and batch costs across pricing tiers.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.