You might try something like this:
function initPlayer(playerQueue){
if(playerQueue.length > 0) {
var player = playerQueue.pop(); // get our options hash for this iteration
var container = $('<div id="'+player.container+'"></div>').appendTo('body');
$(container).jPlayer({
ready: function(){
var _e = this.element;
_e.jPlayer('setFile', player.file);
var timer = setInterval(function(){
if(_e.jPlayer('getData', 'diag.loadPercent') == 100){
$(player.control).click(function(){
// assign your handler
});
clearInterval(timer); // clear the interval
initPlayer(playerQueue); // invoke the next player init
}
},500);
},
/* ... other options ... */
});
}
}
initPlayer([
{container: 'audio-1', file: 'uri/for/file', control: '#button-1'},
{container: 'audio-2', file: 'uri/for/file', control: '#button-2'},
{container: 'audio-3', file: 'uri/for/file', control: '#button-3'},
{container: 'audio-4', file: 'uri/for/file', control: '#button-4'}
]);
Basically we get rid of the explicit loop and instead use the ready function itself to advance the build iteration via the initPlayer
function. By usin an array we can use pop()
which will get us that last element of the array while also removing it from the array. We wait to invoke initPlayer
until after we get a load percent of 100 by polling the load percent of the player every 500 ms.
This is only a suggestion and may need a lot of work... ive never used jPlayer and am flying blind from the documentation so dont expect it to work out of the box :-).