I've got an array with audio-files, to play all one by one. I'm using a javascript player, that will play the audio and provides a callback when finished.
for (i = 0; i < audioFiles.length; i++) {
PlayAudio(audioFiles[i], function(){
alert('complete file #' + i);
});
}
But my problem now, how to do this one by one. The snippet above will start several audio-files and play them parallel. What is the best solution, to wait until a callback is fired?
There are many solutions. Waiting until the callback fires seems like a good solution.
function playAudioFile(index) {
PlaidAudio(audioFiles[index], function () {
var next = index + 1;
if (next < audioFiles.length) {
playAudioFile(index+1);
}
});
}
function playAudioFiles() {
playAudioFile(0);
}
Side note:
If you're looking for a more generic way to run tasks serially, you should look at promises here, here, or here (though the last post is only for AngularJS).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With