I am trying to create a clock from nested while loops but have not succeeded so far
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>reloj</title>
</head>
<body>
<p>Reloj</p>
<script type="text/javascript">
h = 0;
m = 0;
s = 0;
while (h <= 23) {
while (m <= 59) {
while (s <= 59) {
h++;
}
m++;
}
s++;
document.write(h + ":" + m + ":" + s);
}
</script>
</body>
</html>
I've edited it now as far as I've managed to perform:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Reloj</title>
</head>
<body>
<table border 1px solid black>
<tr>
<th>Horas</th>
<th>Minutos</th>
<th>Segundos</th>
</tr>
</table>
<script type="text/javascript">
var vueltash = 0;
var vueltasm = 0;
var vueltass = 0;
var a = "";
h = 0;
m = 0;
s = 0;
while (vueltash <= 23) {
while (vueltasm <= 59) {
while (vueltass <= 59) {
a = "<table border 1px solid black"
+ "<tr>"
+ "<td>" + vueltash + ":" + vueltasm + ":" + vueltass + "<td>"
+ "</tr>"
+ "</table>";
document.write(a);
vueltass++;
}
vueltasm++;
}
vueltash++;
}
</script>
</body>
After creating the loop, I have to insert the clock into a table, I am complicated because I can only use while loops
First error
In your code you are doing this:
What happen?
It's going to iterate infinitely, and the iterations of the third loop won't stop since the evaluated variable
s
never actually increases in value.First Solution
Explanation
You just have to re-order the variables you're executing in your loops, making each one actually increase in value.
second mistake
You shouldn't use
document.write()
to display text that should appear in one place, to make a clock you're better off doing something like this:Explanation
We simply use the
Date()
Javascript function and call it recursively, causing a clock to be generated, so that we get the minutes and seconds continuously and in one place.Update -> Using Loops
Code
Explanation
I have used the Javascript
await
and statementsasync
, which according to some documentation :What gives us to understand that this type of modifiers will wait for the result of a function, that is why we have added:
For that it allows the wait of 1 second before continuing with each one of the instructions.
See example online