0

I'am trying to play sounds respectively using setTimeout. I have an array called challenge which has (for test purposes) [0,1,2,3] and also a function which is play(n, true) for starting the sound and play(n, false) for stopping the sound. What I'am trying to do is:

  • play(0, true).wait1seconds.play(0,false).wait1seconds
  • play(1, true).wait1seconds.play(1,false).wait1seconds and so long.

What I have written so far is:

watch: {
    turn: function(turn) {
        if (this.turn === 0) {
            var self = this;
            var time = 500;
            var timeArray = [[],[]]; // I tried with and without this array
            for (var i = 0; i < this.challenge.length; i ++) {
                timeArray[0][i] = setTimeout(function() {
                    self.play(i, true);
                }, time);
                timeArray[1][i] = setTimeout(function() {
                    self.play(i, false);
                    this.time += 1500; //  // I tried with and without this
                }, time + 1000);
            }
        }
    }
}

Without the array, I just play everything at once and occasionally making a sound which I am able to detect. With the array it's just object error.

Yanek Yuk
  • 74
  • 3
  • 11

1 Answers1

2

Why are you even creating an array if you do not need to reference the timeouts later? You can just "manually" space-out timers by 1 second

// mocking code:
var challenge = [0, 1, 2, 3];

for (let i = 0; i < 2 * challenge.length; i++) {
  setTimeout(function() {
    play(Math.floor(i / 2), i % 2 === 0);
  }, 1000 * i);
}

function play(audioIndex, playAction) {
  if (playAction) {
    console.log("playing audio: " + audioIndex);
  } else {
    console.log("stopping audio: " + audioIndex);
  }
}
Freeman Lambda
  • 3,567
  • 1
  • 25
  • 33
  • Thanks a lot. After changing var to let (which I don't understand and start studying now) and using that clever multiplying by 2 it finally works. My play function is the same as you wrote yourself. But I can not stop wondering what was actually malfunctioning in my code. (I mean the one without that unnecessary array which I hopelessly tried) – Yanek Yuk Jun 19 '17 at 15:47
  • 1
    Good observation, that change from `var` to `let` is not just fancy wording, it is very important and has a very different effect. When you create a function (as inside setTimeout for example) within a for loop, and you use `var` to declare `i`, every function will receive the final value of `i` as its parameter. `let` works around this issue. See https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example and read through the answers, particularly the ES6 answer – Freeman Lambda Jun 19 '17 at 15:55