forked from javascript-tutorial/es.javascript.info
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
69 lines (54 loc) · 1.66 KB
/
index.html
File metadata and controls
69 lines (54 loc) · 1.66 KB
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
<!DOCTYPE HTML>
<html>
<head>
<style>
.hour {
color: red
}
.min {
color: green
}
.sec {
color: blue
}
</style>
</head>
<body>
<div id="clock">
<span class="hour">hh</span>:<span class="min">mm</span>:<span class="sec">ss</span>
</div>
<script>
let timerId;
function update() {
let clock = document.getElementById('clock');
let date = new Date();
let hours = date.getHours();
if (hours < 10) hours = '0' + hours;
clock.children[0].innerHTML = hours;
let minutes = date.getMinutes();
if (minutes < 10) minutes = '0' + minutes;
clock.children[1].innerHTML = minutes;
let seconds = date.getSeconds();
if (seconds < 10) seconds = '0' + seconds;
clock.children[2].innerHTML = seconds;
}
function clockStart() {
// establece un nuevo intervalo solo si el reloj está detenido
// de otro modo sobreescribiríamos la referencia timerID del intervalo en ejecución y no podríamos detener el reloj nunca más
if (!timerId) {
timerId = setInterval(update, 1000);
}
update(); // <-- inicia ahora mismo, no espera 1 second hasta el primer intervalo
}
function clockStop() {
clearInterval(timerId);
timerId = null; // <-- borra timerID para indicar que el reloj fue detenido, haciendo posible iniciarlo de nuevo en clockStart()
}
clockStart();
</script>
<!-- cliquear este botón llama a clockStart() -->
<input type="button" onclick="clockStart()" value="Start">
<!-- cliquear este botón llama a clockStop() -->
<input type="button" onclick="clockStop()" value="Stop">
</body>
</html>