-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathb-timer.js
More file actions
48 lines (39 loc) · 776 Bytes
/
b-timer.js
File metadata and controls
48 lines (39 loc) · 776 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
37
38
39
40
41
42
43
44
45
46
47
48
'use strict';
class Timer {
constructor(interval) {
this.interval = interval;
this.enabled = false;
this.listeners = [];
this.timer = null;
}
on(name, fn) {
if (name === 'timer') {
this.listeners.push(fn);
}
}
start() {
if (!this.enabled) {
this.enabled = true;
this.timer = setTimeout(() => {
this.enabled = false;
for (const fn of this.listeners) fn();
}, this.interval);
}
}
stop() {
if (this.enabled) {
clearTimeout(this.timer);
this.enabled = false;
}
}
}
// Uasge
const timer1 = new Timer(2000);
timer1.on('timer', () => {
console.log('Timer event 1');
});
timer1.on('timer', () => {
console.log('Timer event 2');
});
timer1.start();
timer1.stop();