Incrementing Your Own Loop Variable

Controlling your own loop in n8n can get a little tricky because you have to use values from nodes that are in scope before the loop (initialized) AND within the loop (updated/incremented).

This makes use of the node.isExecuted built in variable, and a JS ternary operator, to decide whether to use the initial value or the value from the last iteration of the loop. Examine the expression in the Increment Loop Var node for details.

Key elements to making this work.

  • All of the expressions must reference specific Set nodes by name (e.g. $('').first().json.page). Nothing can just reference an attribute of the input (immediately previous node) (i.e. NOT $input.first().json.page and NOT $json.page).
  • The initial (first loop iteration) value must be set outside (previous to) the loop.
  • There must be a second Set node within the loop that forwards the value back to the Increment Set node, preferably using a different name (prevPage) at the beginning of the loop, because the Increment node can’t refer to itself in an expression.
  • The increment node’s expression must have the ternary conditional clause (i.e. (test) ? valueIfTrue : valueIfFalse) to choose whether to use the initial value, or increment the value (prevPage) forwarded from the other Set node within the loop.
7 Likes

Pre-emptive reply to myself… I realize this can also be done in Code nodes by referencing $getWorkflowStaticData but each Code node sets up a JS execution sandbox that can slow things down, so if they can be avoided, they probably should be.

1 Like

This is pure genius. The example is really well built and helped me understand the concept without resorting to ChatGPT. Thank you for sharing! :heart:

1 Like

The simplest logic for iterating any value with a loop. It shouldn’t be just limited with pagination. Thank you :love_you_gesture:

@hubschrauber

Do you have an example with a merge node triggering loop ?
I’m having an if condition that triggers a rebuild of one of the input, and it doesn’t trigger again when using 2 merge node.

(If you execute it you will see that it doesn’t repeat forever)

Or simply use

{{$runIndex + 1 }}

Or any other math operation.

It keep count how many times that respective node has runned i n the workflow.

In the end it wasn’t related to the loop but to the merge node not retriggering because not all inputs where reupdated: Double merge node do not retrigger the workflow