generated from davidbonnet/foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sleep.ts
26 lines (24 loc) 路 842 Bytes
/
sleep.ts
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
import { getGlobal } from "../dependencies.js";
const { setTimeout, clearTimeout } = getGlobal();
/**
* Returns a promise that resolves after at least `duration` milliseconds elapsed.
* If a `signal` is provided, listens for an `abort` event to reject the promise with the `signal.reason`.
*
* @param duration Sleep duration in milliseconds.
* @param signal Optional signal parameter on which the `abort` event will be listened to.
* @returns
*/
export function sleep(duration: number, signal?: AbortSignal) {
return new Promise((resolve, reject) => {
const timer = setTimeout(resolve, duration);
if (signal !== undefined) {
if (signal.aborted) {
reject(signal.reason);
}
signal.addEventListener("abort", () => {
clearTimeout(timer);
reject(signal.reason);
});
}
});
}