Skip to content

Commit 04ae023

Browse files
committed
feat: add timeout utility
1 parent 4984933 commit 04ae023

1 file changed

Lines changed: 23 additions & 0 deletions

File tree

src/utils/timeout.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
export function withTimeout<T>(promise: Promise<T>, ms: number, message: string): Promise<T> {
2+
let timer: any;
3+
return Promise.race([
4+
promise,
5+
new Promise<never>((_, reject) => {
6+
timer = setTimeout(() => reject(message), ms);
7+
}),
8+
]).finally(() => clearTimeout(timer));
9+
}
10+
11+
export function parseTimeout(input: string): number {
12+
const match = input.match(/^(\d+)(ms|s|m)$/);
13+
if (!match) return 30000;
14+
const [, value, unit] = match;
15+
switch (unit) {
16+
case "ms":
17+
return +value;
18+
case "s":
19+
return +value * 1000;
20+
case "m":
21+
return +value * 60000;
22+
}
23+
}

0 commit comments

Comments
 (0)