Created
April 16, 2026 20:09
-
-
Save antlis/e42985c2d7c1c6d86915da024b291853 to your computer and use it in GitHub Desktop.
Debounces async functions while canceling previous pending calls. Ideal for search inputs and live queries.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export function debounceAsync(fn, delay = 300) { | |
| let timer; | |
| let rejectPrev; | |
| return (...args) => { | |
| if (timer) clearTimeout(timer); | |
| if (rejectPrev) rejectPrev({ canceled: true }); | |
| return new Promise((resolve, reject) => { | |
| rejectPrev = reject; | |
| timer = setTimeout(async () => { | |
| try { | |
| const result = await fn(...args); | |
| resolve(result); | |
| } catch (e) { | |
| reject(e); | |
| } | |
| }, delay); | |
| }); | |
| }; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use case: