First Error
In your code you are doing this:
while (h <= 23){
while (m <= 59) {
while (s <= 59) {
h++;
}
m++;
}
s++;
}
What's up?
It will be repeated infinitely, and the iterations of the third loop will not stop since the evaluated variable s
never really increases its value.
First Solution
h = 0;
m = 0;
s = 0;
while (h <= 23) {
while (m <= 59) {
while (s <= 59) {
s++;
}
m++;
}
h++;
document.write(h + ":" + m + ":" + s);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>reloj</title>
</head>
<body>
<p>Reloj</p>
</body>
</html>
Explanation
You only have to re-order the variables that you are executing in your loops, making each one really increase its value.
while (h <= 23) {
while (m <= 59) {
while (s <= 59) {
s++;
}
m++;
}
h++;
}
Second Error
You should not use document.write()
to display a text that should appear in one place, to make a clock it is better to do something like this:
function mostrarHora() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = agregarCero(m);
s = agregarCero(s);
document.getElementById('reloj').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(mostrarHora, 500);
}
/**
* Agrega un 0 si el numero esta entre 0 y 9
*/
function agregarCero(i) {
if (i < 10) {
i = "0" + i
};
return i;
}
<body onload="mostrarHora()">
<div id="reloj"></div>
</body>
Explanation
We simply use the function Date()
of Javascript and call it recursively, causing a clock to be generated, so that minutes and seconds are obtained continuously and in the same place.
Update - > Using Loops
Code
async function iniciarReloj() {
/* Valores iniciales */
var hora = 0;
var minuto = 0;
var segundo = 0;
/* Contenedor del reloj */
var contenedor = document.getElementById("reloj");
/* Contenido del reloj */
var reloj;
while (hora <= 23) {
while (minuto <= 59) {
while (segundo <= 59) {
reloj = agregarCero(hora) + ":" + agregarCero(minuto) + ":" + agregarCero(segundo);
contenedor.innerHTML = reloj;
segundo++;
await sleep(1000);
}
minuto++;
segundo = 0;
}
hora++;
minuto = 0;
}
}
/* Iniciamos el reloj */
iniciarReloj();
/**
* Se encarga de realizar una pausa, por N milisegundos
*/
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
/**
* Agrega un 0 si el numero esta entre 0 y 9
*/
function agregarCero(i) {
if (i < 10) {
i = "0" + i
};
return i;
}
<div id="reloj"></div>
Explanation
I have used the sentences await
and async
of Javascript, which according to certain documentation :
Instead of having to use the response of the first request in an uncomfortable then (function () {}), using the special word await we can use getFilm () and getMain () as if they returned synchronous values instead of promises .
What gives us to understand that this type of modifiers wait for the result of a function, that is why we have added:
await sleep(1000);
For allowing the wait of 1 second before continuing with each of the instructions.