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
Setnodes 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.pageand NOT$json.page). - The initial (first loop iteration) value must be set outside (previous to) the loop.
- There must be a second
Setnode within the loop that forwards the value back to theIncrementSetnode, preferably using a different name (prevPage) at the beginning of the loop, because theIncrementnode 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 otherSetnode within the loop.