mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-05-12 19:00:03 +02:00
Refactor model sync scheduling
This commit is contained in:
36
packages/common-lib/eagerDebounceAsync.ts
Normal file
36
packages/common-lib/eagerDebounceAsync.ts
Normal 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);
|
||||
};
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
export * from "./debounce";
|
||||
export * from "./eagerDebounceAsync";
|
||||
export * from "./formatSize";
|
||||
export * from "./templateFunction";
|
||||
|
||||
Reference in New Issue
Block a user