Skip to content

Instantly share code, notes, and snippets.

@antlis
Created April 16, 2026 20:09
Show Gist options
  • Select an option

  • Save antlis/e42985c2d7c1c6d86915da024b291853 to your computer and use it in GitHub Desktop.

Select an option

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.
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);
});
};
}
@antlis
Copy link
Copy Markdown
Author

antlis commented Apr 16, 2026

Use case:

const search = debounceAsync(query => fetch(`/api?q=${query}`).then(r => r.json()), 300);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment