-
Notifications
You must be signed in to change notification settings - Fork 0
/
stopwatch.js
71 lines (59 loc) · 1.66 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
65
66
67
68
69
70
71
function stopwatch (timer) {
let time = 0;
let interval = 0;
let offset = 0;
function update(){
if(this.isOn){
time += delta()
}
let formattedTime = timeFormatter(time);
timer.textContent = formattedTime;
};
function delta (){
let now = Date.now();
let timePassed = now - offset;
offset = now;
return timePassed;
};
function timeFormatter(timeInMilliseconds){
let time = new Date(timeInMilliseconds);
let minutes = time.getMinutes().toString();
let seconds = time.getSeconds().toString();
let milliseconds = time.getMilliseconds().toString();
if (minutes.length < 2){
minutes = '0' + minutes;
}
if (seconds.length < 2){
seconds = '0' + seconds;
}
while (milliseconds.length < 3) {
milliseconds = '0' + milliseconds
}
return minutes + ' : ' + seconds + ' . ' + milliseconds;
};
this.isOn = false;
this.start = function(){
if(!this.isOn){
interval = setInterval(update.bind(this), 10);
offset = Date.now();
this.isOn = true;
document.getElementById('toggle').innerHTML = "Stop";
}
};
this.stop = function(){
if(this.isOn){
clearInterval(interval);
interval = null;
this.isOn = false;
document.getElementById('toggle').innerHTML = "Start";
}
};
this.reset = function(){
if(!this.isOn){
time = 0;
update();
}
};
}
//https://www.youtube.com/watch?v=jRhB1IG7uAw
//21:03