Refactor model sync scheduling

This commit is contained in:
Gregory Schier
2026-05-08 12:57:22 -07:00
parent b0b282535f
commit 471a099b9b
3 changed files with 43 additions and 39 deletions

View File

@@ -0,0 +1,36 @@
export function eagerDebounceAsync(fn: () => Promise<void>, delay: number) {
let timer: ReturnType<typeof setTimeout> | null = null;
let inFlight: Promise<void> | null = null;
let runAfterInFlight = false;
const run = async () => {
if (inFlight != null) {
runAfterInFlight = true;
return;
}
runAfterInFlight = false;
inFlight = fn()
.catch(console.error)
.finally(() => {
inFlight = null;
if (runAfterInFlight && timer == null) {
void run();
}
});
await inFlight;
};
return () => {
if (timer == null) {
void run();
} else {
clearTimeout(timer);
}
timer = setTimeout(() => {
timer = null;
void run();
}, delay);
};
}