-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtimer.ts
78 lines (65 loc) · 1.39 KB
/
timer.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
package main
import "time"
func main() {
ch := make(chan struct{})
go func() {
for i := 0; i < 10; i++ {
ch <- struct{}{}
time.Sleep(100 * time.Millisecond)
}
close(ch)
}()
t := time.NewTimer(300 * time.Millisecond)
for {
select {
case <-ch:
println("tick")
case <-t.C:
println("timeout")
return
}
}
}
*/
import { Chan } from '../chan';
import { select } from '../select';
import { setTimeout as sleep } from 'node:timers/promises';
// Very limited equivalent of time.Timer
// just for testing
// https://github.com/golang/go/blob/master/src/time/sleep.go
class Timer {
public readonly C = new Chan<void>();
constructor(private timeout: number) {
setTimeout(() => this.C.send(), timeout);
}
}
async function main() {
const ch = new Chan<void>();
const t = new Timer(300);
(async () => {
for (let i = 0; i < 10; i++) {
await ch.send();
await sleep(100);
}
ch.close();
})();
for (;;) {
let shouldReturn = false;
await select()
.recv(ch, () => {
console.log('tick');
})
.recv(t.C, () => {
console.log('timeout');
shouldReturn = true;
});
if (shouldReturn) {
return;
}
}
}
main().catch((e) => {
console.error(e);
process.exit(1);
});