-
Notifications
You must be signed in to change notification settings - Fork 2
/
Sleep.ts
31 lines (25 loc) · 855 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
27
28
29
30
import CancellationToken from "cancellationtoken";
export default async function Sleep(ct: CancellationToken, timeout:number):Promise<void>
{
ct.throwIfCancelled();
return new Promise<void>((resolve, reject) => {
let timeObj:NodeJS.Timeout|undefined = setTimeout(()=> {
cleanup();
resolve();
}, timeout);
let unregisterCt:undefined|(()=>void) = ct.onCancelled((reason)=> {
cleanup();
reject(new CancellationToken.CancellationError(reason));
});
const cleanup = ()=> {
if (timeObj !== undefined) {
clearTimeout(timeObj);
timeObj = undefined;
}
if (unregisterCt !== undefined) {
unregisterCt();
unregisterCt = undefined;
}
}
});
}