-2

I've looked at similar questions but can't get setTimeout to work with a forEach loop, even using the index to increase the delay:

pointArray.forEach(function(p) {
    setTimeout(addPt(p, 24, red), pointArray.indexOf(p) * 100000);

});

See that I've increased the delay to a measurable amount of ms and have multiplied by the increasing index - I know the index works as I console log out and it increases up to 100 as that is the array length.

Regardless the console.log I have in addPt happens all at the same time. What is wrong here?

hallucinations
  • 3,424
  • 2
  • 16
  • 23
blue
  • 7,175
  • 16
  • 81
  • 179

1 Answers1

1
addPt(p, 24, red)

You are invoking the method immediately, instead of giving setTimeout a method reference. Such as

setTimeout(addPt, 3000);

However since you are providing inputs, there are a couple ways to do this with a method reference.

//a
setTimeout(function(){ addPt(p, 24, red); }, 3000);
//b
setTimeout(addPt.bind(addPt, p, 24, red), 3000);
//c as noted by Jonas W
setTimeout(addPt, 3000, p, 24, red);

Both will pass a method reference to setTimeout and let -it- execute the function after the duration passes.

Taplar
  • 24,788
  • 4
  • 22
  • 35