-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstopwatch.js
64 lines (53 loc) · 1.22 KB
/
stopwatch.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
function Stopwatch() {
let startTime,
endTime,
running,
duration = 0
Object.defineProperty(this, 'startTime', {
get: function () {
return startTime
},
})
Object.defineProperty(this, 'endTime', {
get: function () {
return endTime
},
})
Object.defineProperty(this, 'running', {
get: function () {
return running
},
})
Object.defineProperty(this, 'duration', {
get: function () {
return duration
},
set: function (value) {
duration = value
},
})
}
Stopwatch.prototype.start = function () {
if (this.running) {
throw new Error('Stopwatch is already started.')
}
this.running = true
this.startTime = new Date()
}
Stopwatch.prototype.stop = function () {
if (!this.running) {
throw new Error('Stopwatch has not started')
}
this.running = false
this.endTime = new Date()
const seconds = (this.endTime.getTime() - this.startTime.getTime()) / 1000
this.duration += seconds
}
Stopwatch.prototype.reset = function () {
this.startTime = null
this.endTime = null
this.running = false
this.duration = 0
}
const sw = new Stopwatch()
//Moving methods to the prototypes to optimize methods but it broke abstraction