forked from dirac-run/dirac
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimeout.ts
More file actions
36 lines (34 loc) · 1011 Bytes
/
timeout.ts
File metadata and controls
36 lines (34 loc) · 1011 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Wait for a condition to become truthy, with a timeout.
* Uses Promise.race for clean timeout handling instead of polling.
*
* @param condition - Function that returns the value to check (truthy = done)
* @param timeoutMs - Maximum time to wait in milliseconds
* @param pollIntervalMs - How often to check the condition (default: 100ms)
* @returns The truthy value if condition is met, or undefined if timeout
*/
export async function waitFor<T>(
condition: () => T | undefined | null,
timeoutMs: number,
pollIntervalMs = 100,
): Promise<T | undefined> {
// Check immediately first
const immediate = condition()
if (immediate) {
return immediate
}
return new Promise((resolve) => {
const intervalId = setInterval(() => {
const result = condition()
if (result) {
clearInterval(intervalId)
clearTimeout(timeoutId)
resolve(result)
}
}, pollIntervalMs)
const timeoutId = setTimeout(() => {
clearInterval(intervalId)
resolve(undefined)
}, timeoutMs)
})
}