user1898657
user1898657

Reputation: 495

javascript iterating through array at certain point

I am trying to iterate through a playlist, but not skip to the next item until the current song is done playing or until a new song in the playlist is chosen. Currently my array is iterated, but does not wait for the current song to finish playing.

HTML:

<li mp3="song1.mp3"></li>
<li mp3="song2.mp3"></li>
<li mp3="song3.mp3"></li>
<li mp3="song4.mp3"></li>

JavaScript:

var player = new MediaElementPlayer('audio');

playlist = ['song1.mp3', 'song2.mp3', 'song3.mp3', 'song4.mp3'];

$('li').click(function() {
  for (var i = playlist.indexOf($(this).attr('mp3')); i < playlist.length; i++) {
    player.setSrc(playlist[i]);
    player.play();
    player.addEventListener('ended', function(e) {
      player.setSrc(playlist[i]);
      player.play();
    }, false);
  }
});

Upvotes: 2

Views: 193

Answers (1)

pimvdb
pimvdb

Reputation: 154968

You're running a plain loop, so a bunch of .play() calls are run right after each other. Instead, run only one .play(), and call the next one when the song has ended. This can be done by calling recursively. Also, use data-mp3 attributes and .data("mp3"), because that's the only valid way to define custom attributes.

$("#playlist li").click(function() {
  var start = playlist.indexOf($(this).data("mp3"));

  (function play(i) {
    if(i < playlist.length) {  // if we're not at the end of the playlist yet
      player.setSrc(playlist[i]);
      player.play();
      player.addEventListener("ended", function(e) {
        play(i + 1);  // done, so call with next index
      }, false);
    }
  })(start);  // call it with first index now
});

Upvotes: 3

Related Questions