Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait until callback

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?

like image 417
Chris Avatar asked Sep 26 '22 06:09

Chris


1 Answers

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).

like image 142
Steven Wexler Avatar answered Sep 30 '22 08:09

Steven Wexler