-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspinner.ts
57 lines (52 loc) · 1.5 KB
/
spinner.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/** 戻り値のIDがclearInterval()によって削除されるまで
* ., .., ...を繰り返しターミナルに表示するロードスピナー
* usage:
* const spinner = new Spinner([".", "..", "..."], 100);
* spinner.start();
* // processing...
* // show spinner ., .., ...
* spinner.stop();
*/
export class Spinner {
private timeout: number | undefined;
private intervalId: number | undefined;
constructor(
private readonly texts: string[],
private readonly interval: number,
private readonly timeup: number,
) {
if (texts.length < 1) {
throw new Error("Texts array must not be empty");
}
if (interval < 0) {
throw new Error("Interval must be a positive number");
}
if (timeup < 0) {
throw new Error("Timeup must be a positive number");
}
}
start(): void {
let i = 0;
const printSpinner = () => {
i = ++i % this.texts.length;
Deno.stderr.writeSync(new TextEncoder().encode("\r" + this.texts[i]));
};
printSpinner();
this.intervalId = setInterval(printSpinner, this.interval);
this.timeout = setTimeout(() => {
this.stop();
throw new Error("Timeout error");
}, this.timeup);
}
stop(): void {
if (this.intervalId !== undefined) {
clearInterval(this.intervalId);
this.intervalId = undefined;
}
if (this.timeout !== undefined) {
clearTimeout(this.timeout);
this.timeout = undefined;
}
Deno.stderr.writeSync(new TextEncoder().encode("\r"));
}
}