-
Notifications
You must be signed in to change notification settings - Fork 2
/
global.html
118 lines (97 loc) · 2.71 KB
/
global.html
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
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Stopwatch</title>
<link rel="stylesheet" href="./css/app.css">
</head>
<body>
<div class="nav">
<a class="hoverHighlight" href="./index.html">< Back</a> | Stopwatch script
</div>
<div class="display">
<div id="timer">00:00:00:000</div>
<button type="button" id="start-button">Start</button>
<button type="button" id="stop-button">Stop</button>
</div>
<script>
var displayNode = document.getElementById("timer"),
startTime = 0,
stopTime = 0,
running = false,
displayInterval;
function isRunning() {
return running;
}
function reset() {
startTime = 0;
stopTime = 0;
}
function start() {
if(!isRunning()) {
running = true;
startTime = startTime + Date.now() - stopTime;
}
}
function stop() {
if(isRunning()) {
running = false;
stopTime = Date.now();
}
}
function time() {
var finalTime = isRunning() ? Date.now() : stopTime;
return finalTime - startTime;
}
function displayTime() {
var totalTime = time() || 0,
milliseconds = parseInt(totalTime % 1000),
seconds = parseInt(((totalTime - milliseconds) / 1000) % 60),
minutes = parseInt(((((totalTime - milliseconds) / 1000) - seconds) / 60) % 60),
hours = parseInt(((((((totalTime - milliseconds) / 1000) - seconds) / 60) - minutes) / 60) % 24);
return padWithZeros(hours, 2) + ":" +
padWithZeros(minutes, 2) + ":" +
padWithZeros(seconds, 2) + ":" +
padWithZeros(milliseconds, 3);
}
function padWithZeros(number, upTo) {
var numberText = number.toString(),
totalChars = numberText.length,
zerosNeeded;
if(totalChars >= upTo) {
return numberText;
}
zerosNeeded = upTo - totalChars;
for(var i = 0; i < zerosNeeded; i++) {
numberText = "0" + numberText;
}
return numberText;
}
function onStart() {
start();
if(!displayInterval) {
displayInterval = setInterval(updateDisplay, 25);
}
}
function updateDisplay() {
displayNode.innerHTML = displayTime();
}
function onStop() {
if(isRunning()) {
stop();
}
else {
reset();
updateDisplay();
}
if(!isNaN(displayInterval)) {
clearInterval(displayInterval);
displayInterval = null;
}
}
// connect buttons
document.getElementById("start-button").addEventListener("click", onStart);
document.getElementById("stop-button").addEventListener("click", onStop);
</script>
</body>
</html>