Why this code is not Playing an Audio?

I’m working on Simon Game and I want to make an error sound when the player click on the wrong button. So, the lines which make the error sound are:

var audioError = playAudio(5);
setTimeout(stopAudio(audioError), 2000);

Where the functions playAudio and stopAudio are:

function playAudio(n) {
  var strAudio = "audio" + n;
  var audio = document.getElementById(strAudio);
  audio.loop = true;
  audio.play();
  
  return audio;
}

function stopAudio(audio) {
  audio.loop = false;
  audio.pause();
}

My audios I put on audio tags in html, like this one:

<audio id="audio5">
  <source src="https://res.cloudinary.com/kurt-johnson/video/upload/v1491432845/simon1_ppd3st.mp3" type="audio/mpeg">
</audio>

When I delete the second line [ setTimeout(stopAudio(audioError), 2000); ] the audio is played, but it is not stopped! So, why the first code above is not playing an Audio when with the second line?

You will have to wrap stopAudio(audioError) inside an anonymous function, because now you are directly calling it.

Basically playAudio() and stopAudio() both run, but directly after each other.

1 Like

It worked now! Thanks!

( I didn’t understand very well why it worked, but no problem… )