0

So I'm trying to console.log each value from a array, but with a delay after each log. It seems it's only waiting 3 seconds, than firing the code logging all at once. Is there any way I could simply log each one after 3 seconds each?

Here's my code:

//Dummy data
const CoordArray = new Array(7).fill(0).map((i, index) => ({XCoord:index, YCoord: index}))

CoordArray.forEach(function(CoordObject) {

  //console.log(key, obj[key]);
  setTimeout(function() {
    console.log(CoordObject.XCoord + " " + CoordObject.YCoord);
  }, 3000);
})
Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
Ownslo
  • 77
  • 1
  • 10
  • 1
    https://www.w3schools.com/jsref/met_win_setinterval.asp – Argee Jul 07 '20 at 08:56
  • 2
    `setTimeout` doesn't block, and the loop is executed within less than a millisecond. Then after 3 secs the callbacks are executed practically in a bunch because they have the same delay. – Teemu Jul 07 '20 at 08:57
  • 1
    Add `i` as a parameter to your function, and use `3000 * i` as a delay – blex Jul 07 '20 at 08:58
  • 3
    you could do the iteration using `setInterval()`, or you could use the index from .forEach to specify each timeout length eg: `3000*i` – Nick Parsons Jul 07 '20 at 08:58
  • Thanks guys/girls. – Ownslo Jul 07 '20 at 09:05

2 Answers2

4

You can do something like this.

const arr = ['5','6','7']
      interval = 3000, //  = 3s
      increment = 1;

arr.forEach(function(el) {
  var run = setTimeout(function() {

    // console each element inside array
    console.log(el);

    clearTimeout(run);
  }, interval * increment);

  increment = increment + 1;
});
xMayank
  • 1,875
  • 2
  • 5
  • 19
2
const CoordArray = new Array(7).fill(0).map((i, index) => ({XCoord:index, YCoord: index}));
var interval = 3000;
var inc = 1;

CoordArray.forEach(function(CoordObject) {
  var run = setTimeout(function() {

    console.log(CoordObject.XCoord + " " + CoordObject.YCoord);
    clearTimeout(run);

  }, interval * inc);

  inc = inc + 1;
});
Parth Shah
  • 1,237
  • 10
  • 24