Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!