Autor Tema: JavaScript setInterval reloj cronómetro cuenta atrás requestAnimationFr CU01164E  (Leído 9639 veces)

bermartinv

  • Avanzado
  • ****
  • APR2.COM
  • Mensajes: 298
    • Ver Perfil
Citar
EJERCICIO 1

Crea un reloj JavaScript que marque los segundos usando el método setInterval.
Código: [Seleccionar]
<!DOCTYPE html>

<html><head><title>Ejemplo aprenderaprogramar.com</title><meta charset="utf-8">

<script type="text/javascript">
 window.onload = function(){
   var llamada = setInterval (reloj,500);
}
 

function reloj() {

    var hoy=new Date(); var h=hoy.getHours(); var m=hoy.getMinutes(); var s=hoy.getSeconds();

    m = actualizarHora(m);    s = actualizarHora(s);

    document.getElementById('displayReloj').innerHTML = h+":"+m+":"+s;

   

}

 

function actualizarHora(i) {

    if (i<10) {i = "0" + i};  // Añadir el cero en números menores de 10

    return i;

}

</script>

 

</head>

<body >

<div style="text-align:center;">

<div id="cabecera"><h2>Cursos aprenderaprogramar.com</h2><h3>Ejemplos JavaScript</h3></div>

<div style="color:blue; font-family: verdana, arial; font-size:30px; padding:15px;" id ="displayReloj" >   </div>

</div>
</body></html>
Citar
EJERCICIO 2

Crea un reloj JavaScript que marque los segundos usando el método requestAnimationFrame.
Código: [Seleccionar]
<!DOCTYPE html>

<html><head><title>Ejemplo aprenderaprogramar.com</title><meta charset="utf-8">

<script type="text/javascript">
var globalID;
    function empecemos(){
        var empezar = requestAnimationFrame(reloj);
}
 

function reloj() {

    var hoy=new Date(); var h=hoy.getHours(); var m=hoy.getMinutes(); var s=hoy.getSeconds();

    m = actualizarHora(m);    s = actualizarHora(s);

    document.getElementById('displayReloj').innerHTML = h+":"+m+":"+s;

    globalID = requestAnimationFrame(reloj);

}



function actualizarHora(i) {

    if (i<10) {i = "0" + i};  // Añadir el cero en números menores de 10

    return i;

}

</script>

 

</head>

<body onload="empecemos()" >

<div style="text-align:center;">

<div id="cabecera"><h2>Cursos aprenderaprogramar.com</h2><h3>Ejemplos JavaScript</h3></div>

<div style="color:blue; font-family: verdana, arial; font-size:30px; padding:15px;" id ="displayReloj" >   </div>

</div>
</body></html>
Citar
EJERCICIO 3

Crea un reloj JavaScript que marque inicialmente 01:00 (es decir, 1 minuto) y que marche hacia atrás (00:59, 00:58, 00:57 … etc.) hasta llegar a 00:00. Cuando llegue a 00:00 debe deternerse y mostrar el mensaje: “Tu tiempo ha terminado”.
Para este ejercicio, me hice un poco de lio porque no sabía cómo hacerlo. Después de termiarlo miré cómo lo habían hecho otros compañeros y la forma que lo había heho Pedro, no hubiese caido nunca de hacerlo por ahí, pero parece más sencilla.
Código: [Seleccionar]
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
<style>
    body{
       
    }
    #ventana{
        margin:auto;
        display:block;
        position:absolute;
        height:200px;
        width:400px;
        background: pink;
        border:solid 1px black;
    }
    #reloj{
        position: absolute;
        top:40px;
        left:120px;
        font-size: 80px;
        color:dodgerblue;
        text-align: center;
    }
</style>
<script>
    var segundos = 0;
    var minutos = 1;
    var llamada;
    var ceromin='';
    var ceroseg='';
   
    function cuentaAtras(){
        devolvercero(minutos,segundos);
        segundos = segundos % 60;
        document.getElementById("reloj").innerHTML=ceromin+minutos+':'+ceroseg+segundos;
         if (minutos ===0 && segundos ===0){
            alert ("Se agotó su tiempo");
            clearTimeOut(llamada);
        }
        if (segundos ==0){
            minutos --;
            segundos+=60;   
        }   
        segundos --;
        var llamada = setTimeout(cuentaAtras,1000);
    }
   
    function devolvercero(minutos,segundos){
        if (minutos<10){
            ceromin='0';
           
        }
        if (segundos<10){
            ceroseg='0';
           
        }else {
            ceroseg='';
        }
         return ceroseg;return ceromin;
    }
   
</script>
</head>
<body onload="cuentaAtras()">
   <div id="ventana">
       <div id="reloj">
           
       </div>
   </div>
</body>
</html>

Saludos
« Última modificación: 27 de Febrero 2016, 11:07 por César Krall »

pedro,,

  • Moderador Global
  • Experto
  • *******
  • APR2.COM
  • Mensajes: 1292
    • Ver Perfil
Re:CU01164E. Reloj y cronometro cuenta atras
« Respuesta #1 en: 25 de Febrero 2016, 23:22 »
Buenas.

Los tres ejercicios bien.

En el ejercicio 3, yo utilicé Date para realizar el ejercicio, pero habría muchas formas de resolver este ejercicio dependiendo el uso para el que se quiera. Aquí te dejo otra forma de resolverlo.

Código: [Seleccionar]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Ejemplo aprenderaprogramar.com</title><meta charset="utf-8">
<script type="text/javascript">
var segundos = 60;
function reloj() {
if(segundos==60){
document.getElementById('displayReloj').innerHTML = '01:00';
}else if(segundos>9){
document.getElementById('displayReloj').innerHTML = '00:' + segundos;
}else{
document.getElementById('displayReloj').innerHTML = '00:' + '0' + segundos;
}
if(segundos==0){
alert('Tu tiempo ha terminado');
}else{
var t = setTimeout(function(){reloj()},1000);
}
segundos--;
}
</script>
</head>
<body onload="reloj()" >
<div style="text-align:center;">
<div id="cabecera"><h2>Cursos aprenderaprogramar.com</h2><h3>Cuenta atrás</h3></div>
<div style="color:blue; font-family: verdana, arial; font-size:30px; padding:15px;" id ="displayReloj" >   </div>
</div>
</body>
</html>

Saludos.

bermartinv

  • Avanzado
  • ****
  • APR2.COM
  • Mensajes: 298
    • Ver Perfil
Re:CU01164E. Reloj y cronometro cuenta atras
« Respuesta #2 en: 25 de Febrero 2016, 23:54 »
El hecho de hacerlo así fue para que se pudiera variar también la cantidad de minutos.
Gracias pedro, por tu aporte. ;)

 

Sobre la educación, sólo puedo decir que es el tema más importante en el que nosotros, como pueblo, debemos involucrarnos.

Abraham Lincoln (1808-1865) Presidente estadounidense.

aprenderaprogramar.com: Desde 2006 comprometidos con la didáctica y divulgación de la programación

Preguntas y respuestas

¿Cómo establecer o cambiar la imagen asociada (avatar) de usuario?
  1. Inicia sesión con tu nombre de usuario y contraseña.
  2. Pulsa en perfil --> perfil del foro
  3. Elige la imagen personalizada que quieras usar. Puedes escogerla de una galería de imágenes o subirla desde tu ordenador.
  4. En la parte final de la página pulsa el botón "cambiar perfil".