PHP - Varios cronometros en la misma pagina web

 
Vista:

Varios cronometros en la misma pagina web

Publicado por muriel (1 intervención) el 21/09/2022 22:20:08
Buenas noches,

Estoy creando una aplicacion web donde necesito tener varios cronometros a la vez y donde se puedan consultar desde diferentes dispositivos.
Tengo un php y un archivo.txt donde guardo la fecha actual creando un cronometro.
Mi itencion es hacerlo con una bbdd y poder tener diferentes cronometros en la misma pagina.
Paso el codigo.
Si pensais que tengo que utilizar js o alguna alternativa soy todo oidos.



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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
<?php
 
$file="hora.txt";
/**
 * Funcion que devuelve la fecha guardada en el archivo de texto
 * Si no existe, lo crea con al fecha actual
 *
 * @return string date
 */
function getFileContent() {
 
    global $file;
 
    return (file_exists($file)) ? file_get_contents($file) : saveFileContent();
 
}
 
/**
 * Funcion que guarda la fecha actual en el archivo de texto
 * El formato del archivo es "YYYY-MM-DD HH:MM:SS"
 *
 * @return string date
 */
 
function saveFileContent() {
 
    global $file;
 
 
 
    $text=date("Y-m-d H:i:s");
 
    file_put_contents($file, $text);
 
    return $text;
 
}
 
 
 
/**
 * Cuando desde javascript mediante AJAX se solicita que se reinicie
 * la fecha, se ejecuta esta condicion y devuelve la nueva fecha para
 * reiniciar el contador.
 */
 
if (isset($_POST["option"]) && $_POST["option"]=="reset") {
 
    echo json_encode(array("data"=>saveFileContent()));
 
    return;
 
}
 
?>
 
<!DOCTYPE html>
 
<html>
 
<head>
 
    <style>
 
    #timer {
 
        font-size:54px;
 
        font-family:Arial;
 
    }
 
    .wrapper {
 
        display:inline-block;
 
        text-align:center;
 
    }
 
    </style>
 
</head>
 
 
 
<body>
    <h1>Cronometro 1</h1>
    <div class="wrapper">
 
        <div id="timer"></div>
 
        <input type="button" id="reset" value="reiniciar cronometro">
 
    </div>
    <h1>Cronometro 2</h1>
    <div class="wrapper">
 
        <div id="timer1"></div>
 
        <input type="button" id="reset" value="reiniciar cronometro">
 
    </div>
 
</body>
 
</html>
 
 
 
<script>
 
// la variable dateServer tiene la fecha guardada en el servidor
 
let dateServer=new Date("<?php echo getFileContent();?>");
 
const timer=document.getElementById("timer");
const timer1=document.getElementById("timer1");
 
 
/**
 * Funcion que muestra la hora con el formato deseado
 * Recibe segundos y devuelve dias : horas : minutos : segundos
 *
 * @param int s - recibe la cantidad de segundos
 *
 * @return string
 */
 
const formatoDuracion = s => {
 
    const time = [
 
        Math.floor(s / 86400),
 
        Math.floor(s / 3600) % 24,
 
        Math.floor(s / 60) % 60,
 
        Math.floor(s / 1) % 60,
 
 
    ];
 
    return time.map((el, i) => i>0 ? ("0"+el).substr(-2) : el).join(" : ");
 
}
 
 
 
/**
 * Evento que se ejecuta al pulsar el boton para actualizar la fecha
 * en el servidor mediante AJAX
 */
 
document.getElementById("reset").addEventListener("click", () => {
 
    var formData = new FormData();
 
    formData.append('option', "reset");
 
 
 
    const options = {
 
        method: 'POST',
 
        body: formData,
 
    }
 
 
 
    fetch(window.location.href, options)
 
        .then(res => res.json())
 
        .then(res => dateServer=new Date(res.data));
 
});
 
 
 
/**
 * Interval que se ejecuta cada segundo y muestra la diferencia de la
 * fecha guardada en el servidor con la fecha actual
 */
 
setInterval(() => {
 
    const DateDiff=new Date()-dateServer;
 
    timer.innerHTML=formatoDuracion(parseInt(DateDiff/1000));
 
}, 1000);
 
</script>
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder