1

all:

I have this loop in which I have a timeout in to try and pause an iteration while an animation and sound finish before it moves on to the next iteration, however; I'm finding that i is not increased when it hits the timeout anonymous function and causes an infinite loop. Here is the code:

var i = 0;

while (i < gamePattern.length - 1) {
  console.log(i);
  buttonAnimation(gamePattern[i]);
  buttonSound(gamePattern[i]);
  setTimeout(() => {
    i++;
  }, 400);
}

I was thinking of trying to set it up with promises, but I don't feel that would actually pause the iteration like I though. Any thoughts or ideas would be greatly appreciated.

Thank you,

Kevin

Shahid Manzoor Bhat
  • 1,307
  • 1
  • 13
  • 32
GainzNerd
  • 312
  • 1
  • 10
  • Does this answer your question? [How to wait until speech is finished inside Loop?](https://stackoverflow.com/questions/58049491/how-to-wait-until-speech-is-finished-inside-loop) – norbitrial Dec 28 '19 at 09:31
  • There are multiple ways to handle this. A straigthforward way is to use a `for` loop instead and use a formula like `i * 400` for the timeout delay. –  Dec 28 '19 at 09:33

1 Answers1

0

Always use let, const. var is old and error prone.

using async/await with promises you can acheive the code waiting timing between iterations

const wait = (cb, time) => {
  return new Promise(res => {
    setTimeout(() => {
      cb();
      res();
    }, time)
  })
}

async function doSomeThing(){
  let i = 0;

  while(i < gamePattern.length-1){
    console.log(i);
    buttonAnimation(gamePattern[i]);
    buttonSound(gamePattern[i]);
    await wait(() => {i++;}, 400)
  }
}
doSomeThing()
shivamg11000
  • 402
  • 1
  • 4
  • 9
  • 3
    why not just `const wait = time => new Promise(resolve => { setTimeout(resolve, time); });` and then `await wait(400); i++;` You shouldn't need a callback for a function that returns a promise... – Patrick Roberts Dec 28 '19 at 09:41