Pablo_Web
Pablo_Web

Reputation: 443

Javascript - Delay audio play

I'm playing an audio when a tooltip is visible, and the script works fine, but I can not find the way to a delay 2 secs the play...

$("#notify")[0].play(); 2000 

What could be wrong?

Thanks in advance!

if (total > 999 && total < 2999) {
  $('#regalo').show();

  if (localStorage.getItem('suppress_gift_tooltip_1') == null) {
    $('.tooltip').show();
    window.setTimeout(function() {
      $('.tooltip').fadeOut('slow');
    }, 6000);

    if (!$("#notify")[0].paused) { //audio
      $("#notify")[0].pause(); //audio
      $("#notify")[0].currentTime = 0; //audio
    } else { //audio
      setTimeout(function() { //audio
        $("#notify")[0].play();
         //audio   
      }, 2000)
    }; //audio

    localStorage.setItem('suppress_gift_tooltip_1', 'true')
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<audio id="notify">
      <source src="audio/notify.ogg" type="audio/ogg">
      <source src="audio/notify.mp3" type="audio/mpeg">
    </audio>

Upvotes: 0

Views: 508

Answers (1)

Rachel Gallen
Rachel Gallen

Reputation: 28553

Use the javascript setTimeout to make this work. You are mis-placing the 2000. Place it after the function brackets (with a comma).

 <script type="text/javascript">
    setTimeout(function(){
      document.getElementById("notify").play(); /* or $("#notify").play() in jquery*/
      //console.log('two second delay!');
    }, 2000)
  </script>

Upvotes: 3

Related Questions