Skip to content

Commit 031add9

Browse files
committed
Add timer class example
1 parent 6db8dcc commit 031add9

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

JavaScript/4-order.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,3 +59,5 @@ fs.readFile('./4-order.js', 'utf8', () => {
5959
fs.readFile('./4-order.js', 'utf8', () => {
6060
console.log('callback #14 readFile');
6161
});
62+
63+
console.log('main ended');

JavaScript/8-ref-unref.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,6 @@ console.dir(timer);
66

77
if (process.argv[2] === '--unref') timer.unref();
88
console.dir(timer);
9+
910
if (process.argv[3] === '--ref') timer.ref();
1011
console.dir(timer);

JavaScript/b-timer.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
'use strict';
2+
3+
class Timer {
4+
constructor(interval) {
5+
this.interval = interval;
6+
this.enabled = false;
7+
this.listeners = [];
8+
this.timer = null;
9+
}
10+
on(name, fn) {
11+
if (name === 'timer') {
12+
this.listeners.push(fn);
13+
}
14+
}
15+
start() {
16+
if (!this.enabled) {
17+
this.enabled = true;
18+
this.timer = setTimeout(() => {
19+
this.enabled = false;
20+
for (const fn of this.listeners) fn();
21+
}, this.interval);
22+
}
23+
}
24+
stop() {
25+
if (this.enabled) {
26+
clearTimeout(this.timer);
27+
this.enabled = false;
28+
}
29+
}
30+
}
31+
32+
// Uasge
33+
34+
const timer1 = new Timer(2000);
35+
36+
timer1.on('timer', () => {
37+
console.log('Timer event 1');
38+
});
39+
40+
timer1.on('timer', () => {
41+
console.log('Timer event 2');
42+
});
43+
44+
timer1.start();
45+
timer1.stop();

0 commit comments

Comments
 (0)