Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

148
Vistas
How to let alert happen only once in a for loop using js?

I am trying to use a button to pause the audio element, and the function works fine except the alert() function. The alert just pop up and stays on the top of the website forever.
here is my HTML code

<button id="threeSecTimer">3s</button>

 <figcaption>Fire</figcaption>
      <audio controls loop>
        <source src="xxx" type="audio/mpeg" />
        Your Browser doesn't support the audio
      </audio>

 <figcaption>Forest</figcaption>
      <audio controls loop>
        <source src="xxx" type="audio/wav" />
        Your Browser doesn't support the audio
      </audio>

here is js

var threeSecTimer = document.getElementById("threeSecTimer");

var allMusic = document.getElementsByTagName("audio");

  function pause3s(e) {
    setTimeout(function () {
      for (var i = 0; i < allMusic.length; i++) {
        if ((allMusic[i] = e.target)) {
          allMusic[i].pause();
          allMusic[i].currentTime = 0;
          alert("time is up!");
        }
      }
    }, 3000);
  }

threeSecTimer.addEventListener("click", pause3s);```

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You have missed an = in your if condition, change (allMusic[i] = e.target) to (allMusic[i] == e.target)

about 4 years ago · Juan Pablo Isaza Denunciar

0

Your condition, (allMusic[i] == e.target) will never be true since e.target is targeting the 3s button, and allMusic[i] is the audo control. That is assuming you changed the single = to a ==, otherwise the condition will always be true, which is not what you want either, but would lead to the alert button popping up twice, once for each audio control. And when the alert is clicked it should disappear, at least it did for me when I tried out your code.

Perhaps you can check HTML5 check if audio is playing? to target the audio that is playing.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda