El Atributo ONTIMEUPDATE

El atributo ontimeupdate se activa periódicamente durante la reproducción de elementos de audio o video, permitiendo sincronizar acciones con la línea de tiempo del contenido multimedia.

El atributo ontimeupdate se activa periódicamente durante la reproducción de elementos <audio> o <video>, permitiendo sincronizar acciones con la línea de tiempo del contenido multimedia. Es ideal para:

  • Actualizar interfaces de tiempo en tiempo real

  • Crear animaciones sincronizadas

  • Implementar subtítulos dinámicos

  • Controlar eventos basados en marcas de tiempo


???? Sintaxis básica

html
Copy
<!-- En HTML -->
<video 
    src="video.mp4" 
    controls 
    ontimeupdate="manejarTiempo(event)"
></video>

<!-- En JavaScript -->
<script>
  const video = document.getElementById("miVideo");
  video.addEventListener("timeupdate", (event) => {
    // Lógica aquí
  });
</script>

???? Propiedades clave

  • currentTime: Tiempo actual de reproducción (en segundos).

  • duration: Duración total del contenido (en segundos).

  • playbackRate: Velocidad de reproducción (1.0 = normal).


???? Ejemplos prácticos

1. Mostrar tiempo actual y duración

html
Copy
<video id="reproductor" src="video.mp4" controls></video>
<div>
  <span id="tiempoActual">00:00</span> / 
  <span id="duracionTotal">00:00</span>
</div>

<script>
  const video = document.getElementById("reproductor");
  
  video.addEventListener("timeupdate", () => {
    document.getElementById("tiempoActual").textContent = 
      formatearTiempo(video.currentTime);
    
    if (video.duration) {
      document.getElementById("duracionTotal").textContent = 
        formatearTiempo(video.duration);
    }
  });

  function formatearTiempo(segundos) {
    const minutos = Math.floor(segundos / 60);
    const segs = Math.floor(segundos % 60);
    return `${minutos.toString().padStart(2, '0')}:${segs.toString().padStart(2, '0')}`;
  }
</script>

2. Barra de progreso personalizada

html
Copy
<video id="videoPlayer" src="video.mp4" controls></video>
<div class="progress-container">
  <div id="progressBar" class="progress"></div>
</div>

<style>
  .progress-container {
    width: 100%;
    height: 5px;
    background: #ddd;
    cursor: pointer;
  }
  .progress {
    height: 100%;
    width: 0%;
    background: #2ecc71;
    transition: width 0.1s linear;
  }
</style>

<script>
  const video = document.getElementById("videoPlayer");
  const progressBar = document.getElementById("progressBar");
  
  video.addEventListener("timeupdate", () => {
    const porcentaje = (video.currentTime / video.duration) * 100;
    progressBar.style.width = `${porcentaje}%`;
  });

  // Click en la barra para saltar a posición
  document.querySelector(".progress-container").addEventListener("click", (e) => {
    const rect = e.target.getBoundingClientRect();
    const pos = (e.clientX - rect.left) / rect.width;
    video.currentTime = pos * video.duration;
  });
</script>

???? Casos de uso avanzados

1. Sistema de subtítulos dinámicos

html
Copy
<video id="documental" src="nature.mp4" controls></video>
<div id="subtitulos" class="subtitulos"></div>

<script>
  const subtitulos = [
    { start: 5, end: 10, text: "El león es el rey de la sabana" },
    { start: 15, end: 20, text: "Las jirafas pueden alcanzar hasta 5 metros" }
  ];

  video.addEventListener("timeupdate", () => {
    const currentTime = video.currentTime;
    const subtitulo = subtitulos.find(s => currentTime >= s.start && currentTime <= s.end);
    document.getElementById("subtitulos").textContent = subtitulo?.text || "";
  });
</script>

<style>
  .subtitulos {
    position: fixed;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    background: rgba(0,0,0,0.7);
    color: white;
    padding: 10px;
    border-radius: 5px;
  }
</style>

2. Controlador de eventos por tiempo

javascript
Copy
const eventos = [
  { time: 10, action: () => mostrarNota("¡Primer hito importante!") },
  { time: 30, action: () => cambiarCamara("vista-aerea") },
  { time: 45, action: () => pausarParaCuestionario() }
];

video.addEventListener("timeupdate", () => {
  eventos.forEach(evento => {
    if (Math.floor(video.currentTime) === evento.time && !evento.ejecutado) {
      evento.action();
      evento.ejecutado = true;
    }
  });
});

⚠️ Consideraciones importantes

1. Optimización de rendimiento

  • Evitar cálculos pesados: El evento se dispara ~4-66 veces por segundo.

  • Usar requestAnimationFrame:

    javascript
    Copy
    video.addEventListener("timeupdate", () => {
      requestAnimationFrame(() => {
        // Actualizaciones de UI aquí
      });
    });

2. Precisión temporal

javascript
Copy
// Para sincronización exacta (ej: 24 fps)
const frameRate = 24;
video.addEventListener("timeupdate", () => {
  const frameActual = Math.floor(video.currentTime * frameRate);
  // Lógica por frame
});

3. Compatibilidad

Navegador Soporte
Chrome ✅ 15+
Firefox ✅ 12+
Safari ✅ 6+
Edge ✅ 12+

???? Buenas prácticas

  1. Limpiar listeners cuando no sean necesarios:

    javascript
    Copy
    const handler = () => { /* ... */ };
    video.addEventListener("timeupdate", handler);
    // Para remover:
    video.removeEventListener("timeupdate", handler);
  2. Combinar con onseeked para manejar saltos de tiempo:

    javascript
    Copy
    video.addEventListener("seeked", () => {
      console.log("Nueva posición:", video.currentTime);
    });
  3. Manejar NaN y valores infinitos:

    javascript
    Copy
    if (!isNaN(video.duration) && isFinite(video.duration)) {
      // Lógica segura
    }

???? Conclusión

El atributo ontimeupdate es fundamental para:

  • Crear reproductores multimedia personalizados

  • Implementar sistemas educativos interactivos

  • Desarrollar experiencias de videojuegos basadas en tiempo

  • Construir aplicaciones de edición de video/audio

Ejemplo final avanzado (Reproductor educativo):

html
Copy
<video id="curso" src="clase.mp4" controls></video>
<div id="puntosClave"></div>

<script>
  const puntosClave = {
    15: "Concepto 1: Fundamentos de HTML",
    90: "Concepto 2: Introducción a CSS",
    180: "Ejercicio práctico"
  };

  video.addEventListener("timeupdate", () => {
    const tiempo = Math.floor(video.currentTime);
    const concepto = puntosClave[tiempo];
    
    if (concepto) {
      const elemento = document.getElementById("puntosClave");
      elemento.innerHTML = `<h3>${concepto}</h3>`;
      elemento.style.animation = "destacar 1s";
    }
  });
</script>

<style>
  @keyframes destacar {
    from { background: #2ecc71; }
    to { background: transparent; }
  }
</style>

Con estos conceptos, podrás crear experiencias multimedia ricas y altamente interactivas. ¡Experimenta con diferentes implementaciones! ????????