-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontext.js
More file actions
36 lines (31 loc) · 839 Bytes
/
context.js
File metadata and controls
36 lines (31 loc) · 839 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
import { sleepMillis } from "./utils.js";
export class ContextCancellation extends Error {
constructor() {
super('Cancellation');
this.name = 'ContextCancellation';
}
}
export class Context {
constructor(maxLagMillis) {
this._cancelFlag = false;
this._maxLagMillis = maxLagMillis;
}
setCancelFlag(flag) {
this._cancelFlag = flag;
}
maybeThrowForCancel() {
if (this._cancelFlag) {
this._cancelFlag = false;
throw new ContextCancellation();
}
}
async sleepMillis(ms) {
const maxLag = this._maxLagMillis;
for (; ms > maxLag; ms -= maxLag) {
this.maybeThrowForCancel();
await sleepMillis(maxLag);
}
this.maybeThrowForCancel();
await sleepMillis(ms);
}
}