-
-
Notifications
You must be signed in to change notification settings - Fork 70
/
clock.js
executable file
·79 lines (62 loc) · 1.15 KB
/
clock.js
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
79
#!/usr/bin/env node
'use strict';
const Emittery = require('..');
class Clock extends Emittery {
constructor() {
super();
this.startedAt = 0;
this.timer = null;
}
tick() {
if (!this.timer) {
this.emit('error', new Error('Clock has not been started'));
return;
}
const now = Date.now();
const duration = now - this.startedAt;
this.emit('tick', {duration, now});
}
start() {
if (this.timer) {
throw new Error('Clock has already been started');
}
this.startedAt = Date.now();
this.timer = setInterval(this.tick.bind(this), 1000);
this.emit('start');
}
stop() {
if (this.timer) {
clearInterval(this.timer);
}
this.startedAt = 0;
this.timer = null;
this.emit('stop');
}
}
function onTick({duration}) {
console.log(Math.floor(duration / 1000));
if (duration >= 6000) {
stop();
}
}
function onError(err) {
process.exitCode = 1;
console.error(err);
stop();
}
const timer = new Clock();
const offTick = timer.on('tick', onTick);
const offError = timer.on('error', onError);
function stop() {
offTick();
offError();
timer.stop();
}
timer.start();
// Prints:
// 1
// 2
// 3
// 4
// 5
// 6