How do I add a delay to each iteration of a foreachloop?

The loop fires in a sequence that goes like this:

  1. Initialize the index variable.
  2. If the length of the array is greater than current index do the loop body of index else go to #4
  3. When the body finishes Increment the index go to #2
  4. Complete

When the loop body hits a delay it sets up a timer and delegate to execute the rest of the body when the timer elapses. This effectively ends the execution of the loop body as far as the loop is concerned and so it goes on to the next loop body. The delay node that you call in all subsequent loop bodies is the same node you called in the first and so execution ends so that the global tick can continue and only a single loop body is evaluated when the timer finishes.

Why doesn’t a delay register a new event every time it is called? It’s intended to delay the execution of some logic a set amount of time. If set up new events every time it was hit then it would just cause a flood of delayed calls at the end of its timer but without actually spacing them apart. In effect it is a DoOnceInXSecondsThenReset node. Just like DoOnce it ends the execution path until it is reset.

Delays and standard foreach loops just can’t get along because the loop doesn’t know that you ended execution of the loop body with a delay. It must finish execution within a single tick because the loop state is not saved between ticks.

The answer as stated by others is to duplicate the logic of a foreach loop but to store the index so that you can continue the next loop body after the delay has finished.

I would also suggest that setting up a Timer would be cleaner and more straight forward at this point because you don’t have to loop the wires back to the start.

You can do this do this by creating a custom event and name it relevant do whatever it is you need to do such as “TrySpawnNextActor” then At the end of the loop place a timer that will call your event. This is the fire and forget way of doing it. The loop will end when you reach the last index of the array because no more timers will be set up.

You should guard the loop with a branch/if statement so that outside calls can’t call your loop again while it is executing possibly causing duplication or premature completion or lead to the loop completion being called twice. Not a problem with normal loops because they execute all at once.

4 Likes