0

i got on website some audio notification sounds. it plays when something happens. but i need to make it loops for x times. i want it to do as easiest way as possible so i think i can use setTimeout function. but somehow it don't work. this is my code:

var snd = new Audio("sound.mp3");
if (num1 == balance){
 snd.play();
 setTimeout(function() {snd.play()},500);
}

i don't get any error, it's just don't work. the sound plays only once. what's wrong with my code? thank you

Adamo
  • 121
  • 1
  • 6
  • 1
    Possible duplicate of [Why won't my HTML5 audio loop?](https://stackoverflow.com/questions/7747526/why-wont-my-html5-audio-loop) – Durga Aug 27 '18 at 11:10
  • `setTimeout` does exactly what its name says: It executes code after a certain period of time. If at that point, the sound is already playing, I assume `Audio.prototype.play()` won't restart it, instead it'll probably do nothing. – connexo Aug 27 '18 at 11:12
  • @connexo thx.. you are right.. my code is ok i just have very little delay set.. – Adamo Aug 27 '18 at 11:15

2 Answers2

1

Let's say you want it play 5 times.

var snd = new Audio("sound.mp3");
var times = 0;
function play(){
    snd.play();
    times++;
    if(times < 5) setTimeout(play, 500);
}
setTimeout(play, 500);
NoobTW
  • 2,466
  • 2
  • 24
  • 42
0

As I understand your question, you want to loop the sound over and over again. So you need to use setInterval instead of setTimeout, so that the callback is triggered after the set interval. Also, use named function so that you can clear the interval after the condition is satisfied.

Please refer: https://www.w3schools.com/jsref/met_win_clearinterval.asp for more information regarding the code.

Note:

  1. setTimeout - will call your function only once after the set time has elapsed.
  2. setInterval - will call your function again and again with the time delay mentioned.
Sulokit
  • 137
  • 3