-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstopwatch.js
63 lines (60 loc) · 1.44 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
Array.prototype.sum = function(){
var total = 0;
for (var i = 0; i < this.length; i++){
if (!isNaN(this[i])) {
total += Number(this[i]);
}
}
return total;
};
var StopWatch = function(callback, callbackOn){
this.reset();
setTimeout(callback, callbackOn);
};
// public methods
StopWatch.prototype.start = function(){
if (this.isActive) return false;
this.startProcess();
return true;
};
StopWatch.prototype.stop = function(){
if (!this.isActive) return false;
this.stopProcess();
return true;
};
StopWatch.prototype.reset = function(){
this.clearProcess();
this.lapTimes = [];
this.isActive = false;
};
StopWatch.prototype.lap = function(){
if (this.isActive){
this.addLapTime();
return true;
}
return false;
};
StopWatch.prototype.getTotalTime = function(){
return this.lapTimes.sum();
};
// private methods
StopWatch.prototype.addProcess = function(){
this.processTime = Date.now() - this.startTime;
this.timeoutID = setTimeout(this.addProcess.bind(this), 1);
};
StopWatch.prototype.startProcess = function(){
this.startTime = Date.now() - this.processTime;
this.addProcess();
this.isActive = true;
};
StopWatch.prototype.stopProcess = function(){
clearTimeout(this.timeoutID);
this.isActive = false;
};
StopWatch.prototype.clearProcess = function(){
this.processTime = 0;
};
StopWatch.prototype.addLapTime = function(){
this.lapTimes.push(this.processTime);
this.startTime = Date.now();
};