Skip to content

Commit 17211fe

Browse files
committed
refactor: add state to DelayedTimeout
1 parent e8e3862 commit 17211fe

File tree

3 files changed

+28
-6
lines changed

3 files changed

+28
-6
lines changed

src/commands/analyse.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ async function rutine(ext: Ext, args?: string[]) {
110110

111111
export default async function analyse(ext: Ext, ms?: number, args?: string[]) {
112112
await stopAnalyse(ext);
113-
ext.store.analyse.timeout(async () => {
113+
ext.store.analyse.timeout.run(async () => {
114114
await rutine(ext, args);
115115
}, ms ?? ext.settings.analysedDelay);
116116
}

src/extension.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,7 @@ export class Ext<
211211
tag: `event:${eventName}`,
212212
message: path,
213213
});
214-
this.store.reactivate.timeout(() => this.reactivate());
214+
this.store.reactivate.timeout.run(() => this.reactivate());
215215
}
216216
);
217217

src/utils/async.ts

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,31 @@
1-
export type DelayedTimeout = (cb: () => unknown, ms?: number) => void;
1+
export type DelayedTimeout = {
2+
readonly running: boolean;
3+
readonly pending: boolean;
4+
run: (cb: () => unknown, ms?: number) => void;
5+
};
26

37
export function createDelayedTimeout(defaultsMs?: number) {
48
let timeout: NodeJS.Timeout | undefined;
5-
return (cb: () => unknown, ms = defaultsMs) => {
6-
if (timeout) clearTimeout(timeout);
7-
timeout = setTimeout(cb, ms);
9+
let running = false;
10+
let pending = false;
11+
return {
12+
get pending() {
13+
return pending;
14+
},
15+
get running() {
16+
return running;
17+
},
18+
run: (cb: () => unknown, ms = defaultsMs) => {
19+
pending = true;
20+
if (timeout) clearTimeout(timeout);
21+
timeout = setTimeout(async () => {
22+
running = true;
23+
try {
24+
await cb();
25+
} finally {
26+
running = pending = false;
27+
}
28+
}, ms);
29+
},
830
};
931
}

0 commit comments

Comments
 (0)