Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

149
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda