-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
124 lines (87 loc) · 2.5 KB
/
app.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
app = angular.module('watchApp', []);
app.directive('stopwatch', function () {
return {
restrict: 'E',
scope: {
name: '@'
},
templateUrl: 'stopwatch.html',
link: function (scope, elem, attrs) {
scope.state = 'idle';
scope.worker = new Worker('worker.js');
scope.totalDuration = 0;
scope.history = [];
function exportData() {
var data = "text/json;charset=utf-8," + JSON.stringify(scope.history);
var a = document.createElement('a');
a.href = 'data:' + data;
a.download = (scope.name || 'history') + '.json';
a.click();
}
function initWorker (worker) {
worker.addEventListener('message', function(e) {
var workerData = e.data;
switch (workerData.msg) {
case 'update':
scope.totalDuration = workerData.time;
break;
case 'split':
scope.history.push(workerData.time);
break;
case 'end':
scope.history.push(workerData.time);
scope.totalDuration = workerData.time.totalDuration;
exportData();
break;
}
scope.$apply();
});
}
scope.start = function () {
// console.log('app start');
if (scope.state === 'idle') {
scope.worker = scope.worker || new Worker('worker.js');
initWorker(scope.worker);
scope.state = 'busy';
var startTime = Date.now();
scope.worker.postMessage({msg: 'start', time: startTime});
}
};
scope.split = function () {
// console.log('app split');
if (scope.state === 'busy') {
var currentTime = Date.now();
scope.worker.postMessage({msg: 'split', time: currentTime});
}
};
scope.reset = function () {
// console.log('app reset');
scope.state = 'idle';
scope.history = [];
scope.totalDuration = 0;
if (scope.worker) {
scope.worker.terminate();
scope.worker = undefined;
}
};
scope.stop = function () {
// console.log('app stop');
var currentTime = Date.now();
scope.worker.postMessage({msg: 'stop', time: currentTime});
scope.state = 'stop';
};
}
};
});
app.filter('stopwatch', function () {
return filterTime;
});
function filterTime(timeInMs) {
var hours = Math.floor(timeInMs / 36e5);
timeInMs %= 36e5;
var mins = Math.floor(timeInMs / 6e4);
timeInMs %= 6e4;
var secs = Math.floor(timeInMs / 1000);
timeInMs %= 1000;
return hours + ' hr : ' + mins + ' min : ' + secs + ' sec : ' + timeInMs + ' ms';
}