Function after forEach end

I’m working on a Simon Game, the game work well, no problem, but i want to add something, at the start the situation it’s this

gamePattner = []

so the code started the new Sequence when the game it’s avvied;

but then when gamePattner have element i want that for every element start this code

gamePattner.forEach((item, index) => {
  setTimeOut(() => {
 // do things with element
}, index * 1000)
})

then after finish this forEach add new element on the sequence, but it’s not wait the forEeach end and do the code after, how i can do wait that the forEach end and the go the other part of code

May I ask you a few questions?

  1. Your Js is client-side or server-side (Node.js)?
  2. Have you checked your console yet?

Update:

Without error report, I think my best assumption is you make a spelling mistake on setTimeOut it should be setTimeout. Also, you need to call it from window object. Why don’t you try this:

gamePattner.forEach((item, index) => {
  window.setTimeout(() => {
 // do things with element
}, index * 1000)
})

Here is a demonstration from fiddle.

It sounds like you want to handle asynchronous behavior so you don’t end up with, say, undefined values.

async and await are your friends :slight_smile:

Consider the following code (not exactly your situation, but you’ll see how to relate it to yours).
We want to take an array arr and, for each element in it, concatenate it and the string 'add'
so that we get ['add salt', 'add pepper', 'add sage', 'add rosemary'].

var arr = ['salt', 'pepper', 'sage', 'rosemary'];

function concatenator(y) {
    setTimeout(() => {
      let added = 'add '+ y;
      return added;
    }, 500);
}

function delayedIterator(x) {
  var newArr = [];
  x.forEach((elem) => {
    const newElem = concatenator(elem);
    newArr.push(newElem)  
  })
  console.log(newArr);
}

delayedIterator(arr);

When we run the code, we get in the console:

[ undefined, undefined, undefined, undefined ]
[Finished in 1.368s]

However, if we use async and await and write things a little differently:

var arr = ['salt', 'pepper', 'sage', 'rosemary'];

function concatenator(y) {
  return new Promise ((resolve) => {
    setTimeout(() => {
      let added = 'add '+ y;
      resolve(added);
    }, 500);
  })
}

async function delayedIterator(x) {
  var newArr = [];
  for (const elem of x) {
    const newElem = await concatenator(elem);
    newArr.push(newElem);
  }
  console.log(newArr);
}

delayedIterator(arr);

we get in the console:

[ 'add salt', 'add pepper', 'add sage', 'add rosemary' ]
[Finished in 2.893s]

Instead of Array.forEach(), we used for…of.

thanks both for the Answer, i find how do work how i want, i used two setTimeout at the end, work very well