Eventos de tiempo en Javascript
El método «setInterval()» esperará un número en milisegundos que son especificados en el código y ejecutará la acción en ese intervalo de tiempo.
El método «setTimeout()» ejecutará una sóla acción pasado el tiempo especificado en el código.
El método «clearInterval» o «clearTimeout» detendrá los métodos correspondientes.
Veamos su sintaxis:
/*El primer parámetro debe ser una función
El segundo parámetro debe indicar la longitud del intervalo
de tiempo en cada ejecución*/
setInterval("javascript function",milisegundos");
setTimeout("javascript function",milisegundos");
Si metemos setTimeout en una variable de la siguiente forma,
podemos pararlo así:
clearInterval(variable);
clearTimeout(variable);
En el siguiente ejemplo, se simula un registro de desplazamiento que he llamado «Juego de Luces»:
Puedes ver su funcionamiento aquí.
También tienes una versión realizada con imágenes, aquí.
Código HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.1 Strict//EN" "http://www.w3.org/TR/html4.1/DTD/html4.1-Strict.dtd"> <html> <head> <title>Juego de Luces</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width"> <meta name="author" content="José Campo"> <link rel="stylesheet" type="text/css" href="css/estilos.css"> <script type="text/javascript" src="js/animacionLuces.js"></script> </head> <body> <div id="conjunto"> <h4 id="titulo">Juego de luces</h4> <div id="primera"></div> <div id="segunda"></div> <div id="tercera"></div> <div id="cuarta"></div> <div id="quinta"></div> </div><div id="botones"> <input name="Animar" id="empezar" type="button" value="Animar" class="animar" /> <input name="Parar" id="parar" type="button" value="Parar" class="parar" /> </div> </body> </html>
Código CSS:
/*Created on : 29-nov-2013, 22:29:36Author : José Campo*/
#conjunto
{
margin-left:20%;
}
#primera {
position:absolute;
width: 100px;
height: 100px;
background-color: black;
display: inline;
}
#segunda {
position:absolute;
width: 100px;
height: 100px;
background-color: black;
margin-left:110px;
display:inline;
}
#tercera {
position:absolute;
width: 100px;
height: 100px;
background-color: black;
margin-left: 220px;
display: inline;
}
#cuarta {
position:absolute;
width: 100px;
height: 100px;
background-color: black;
margin-left: 330px;
display:inline;
}
#quinta {position:absolute;
width: 100px;
height: 100px;
background-color: black;
margin-left: 440px;
display:inline;
}
.animar {
position:absolute;
font-size: 50px;
margin-top: 10%;
margin-left: 25%;
}
.parar {
position: absolute;
font-size: 50px;
margin-top: 10%;
margin-left: 45%;
}
Código Javascript:
//Este código realiza la animación haciendo el efecto del juego de luces
/*Comenzamos indicando a javascript que cuando se haga click en el botón animar,
ejecute la función empezar, esto lo hará cuando se termine de cargar la página*/
window.onload = function() {
//Asignamos la función externa al botón animar y parar
document.getElementById('empezar').onclick = comenzar;
document.getElementById('parar').onclick = parar;
};
var tiempo = setTimeout;
var flag;
function comenzar() {
flag = 0;
document.getElementById('titulo').textContent = "...comienza el espectáculo";
tiempo(function() {
encenderPrimera();}, 300);
}
function encenderPrimera() {
if (flag === 0) {
document.getElementById('quinta').style.backgroundColor = "black";
document.getElementById('primera').style.backgroundColor = "red";
tiempo(function() {
encenderSegunda();}, 300);
}
}
function encenderSegunda() {
if (flag === 0) {
document.getElementById('primera').style.backgroundColor = "black";
document.getElementById('segunda').style.backgroundColor = "red";
tiempo(function() {
encenderTercera();}, 300);
}
}
function encenderTercera() {
if (flag === 0) {
document.getElementById('segunda').style.backgroundColor = "black";
document.getElementById('tercera').style.backgroundColor = "red";
tiempo(function() {
encenderCuarta();}, 300);
}
}
function encenderCuarta() {
if (flag === 0) {
document.getElementById('tercera').style.backgroundColor = "black";
document.getElementById('cuarta').style.backgroundColor = "red";
tiempo(function() {
encenderQuinta();}, 300);
}
}
function encenderQuinta() {
if (flag === 0) {
document.getElementById('cuarta').style.backgroundColor = "black";
document.getElementById('quinta').style.backgroundColor = "red";
tiempo(function() {
encenderPrimera();}, 300);
}
}
function parar() {
document.getElementById('primera').style.backgroundColor = "black";
document.getElementById('segunda').style.backgroundColor = "black";
document.getElementById('tercera').style.backgroundColor = "black";
document.getElementById('cuarta').style.backgroundColor = "black";
document.getElementById('quinta').style.backgroundColor = "black";
document.getElementById('titulo').textContent = "Juego de Luces";
flag = 1;
}