Chris Swinson
Chris Swinson

Reputation: 19

setTimeOut not working as expected in function

For some reason, the setTimeOut variable in my function does not work. I have tried a few different strategies, but none have worked. Basically, I am attempting to set a delay before the audio plays. Below is both my JS and HTML code.

function song(musicfile) {
  $('#result').html("<audio autoplay=\"true\"><source src=" + musicfile + " type=\"audio/mpeg\" /></audio>");
  setTimeout(song, 10000);
}
<img class="playbutton1 center-block" src="play.png" onclick="song('pretender.m4a');">

Upvotes: 0

Views: 1530

Answers (2)

cHao
cHao

Reputation: 86506

Of course there's no delay. Someone clicks the image, you immediately inject the <audio> element, and then set a delay.

What you need is to setTimeout(function_that_injects_the_element, 10000).

function song(musicfile) {
  setTimeout(function() {
    $('#result').html("<audio autoplay=\"true\"><source src=" + musicfile + " type=\"audio/mpeg\" /></audio>");
  }, 10000);
}

I might suggest also removing any existing audio elements, or at least stopping them if possible.

Upvotes: 2

Dan Raps
Dan Raps

Reputation: 318

The jquery call should be inside the setTimeout

function song(musicfile) {

  setTimeout(function(){$('#result').html("<audio autoplay=\"true\"><source src=" + musicfile + " type=\"audio/mpeg\" /></audio>");}, 10000);
}

Upvotes: 1

Related Questions