-
Notifications
You must be signed in to change notification settings - Fork 179
Expand file tree
/
Copy pathwait.ts
More file actions
53 lines (44 loc) · 1.61 KB
/
Copy pathwait.ts
File metadata and controls
53 lines (44 loc) · 1.61 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
const MAX_TIMER = 2 ** 31 - 1; // ~25 days
export interface WaitOptions {
/**
* SetTimeout function to be used by wait.
*
* @param callback - A function to be executed after the timer expires.
* @param delay - The time, in milliseconds that the timer should wait before the specified function is executed.
*/
readonly setTimeout?: (callback: Function, delay: number) => void;
}
/**
* Returns a Promise that resolves after the requested timeout.
*
* @param timeout - The number of milliseconds to wait before resolving the Promise.
* @param returnValue - The value that the Promise will resolve to.
* @returns A Promise that resolves with `returnValue`.
*/
export function wait<T = void>(
timeout?: bigint | number | undefined,
returnValue?: T,
options?: WaitOptions,
): Promise<T> {
if (typeof timeout !== 'number' && typeof timeout !== 'bigint' && timeout !== undefined) {
throw new TypeError('Timeout must be a number or bigint');
}
if (typeof timeout === 'bigint') {
timeout = Number(timeout);
}
if (timeout! >= Number.MAX_SAFE_INTEGER) {
// Thousands of years
timeout = Infinity;
}
return new Promise((resolve) => {
const _setTimeout = options?.setTimeout ?? setTimeout;
const activate = () => {
const time = Math.min(timeout as number, MAX_TIMER);
timeout = (timeout as number) - time;
_setTimeout(() => ((timeout as number) > 0 ? activate() : resolve(returnValue as T)), time);
};
if (timeout !== Infinity) {
activate();
}
});
}