Search code examples
javascriptfor-loopaudiosettimeout

Output timed audio from 2 looped arrays [Javascript]


I have two arrays, array A and array B. There are an equal amount of values inside of each array, but the arrays change length, having a maximum length of 6. What I'm trying to achieve is to play two sounds, one from array A and one from B one after another, 1-6 times, depending on the array length. Like this:

  • Play sound 1 from array 1.
  • wait a second
  • Play sound 1 from array 2.
  • wait two seconds.
  • (repeat)
  • Play sound 2 from array 1.
  • wait a second
  • Play sound 2 from array 2.
  • wait two seconds.
    (and so on...)

Attempt 1

for (var i=0; i<=numberOfValues-1; i++){
    setTimeout(function(){playSoundArray1[i];},1000);
    setTimeout(function(){playSoundArray2[i];},2000);
}

Attempt 2

function externalTimeout(i, array, time){
    setTimeout(function(){array[i];},time);
}

for (let i=0; i<=numberOfValues-1; i++){
    externalTimeout(i,playSoundArray1,1000);
    externalTimeout(i,playSoundArray2,2000);
}

Attempt two partially works, it plays all the sounds from the first array "together", and then plays all the sounds from the second array "together".
I do understand why these don't work, but I cannot come up with a solution. Suggestions? Thanks!


Solution

  •      var a   = [1,2,3];
          var b   = [4,5,6];
          var i   = 0;
          update();
          
          function update(){
          
                if(i===a.length){
                      console.log('complete');
                      return;
                }
                
                playa(i);
                
                i++;
                
          }//update
                
          
          function playa(i){
                
                console.log(a[i]);
                setTimeout(playb,1000,i);
                
          }//playa
          
          function playb(i){
          
                console.log(b[i]);
                setTimeout(update,2000);
                
          }//playb