Thanks for sharing the screenshots. I see exactly what is happening, and it is a very common in n8n loops…
You aren’t doing anything wrong with the JavaScript itself. The issue is your Check status node.
When an HTTP Request node runs, its default behavior is to output only the new data it just fetched, overwriting the previous item data. So, when your workflow loops back around, the Check status node completely drops the counter variable you created in the previous run. By the time the data reaches your Code node again, item.json.counter is gone, so it evaluates as undefined and starts over at 1.
you have to tell the Check status node to stop throwing away the input data.
-
Open your
Check statusnode. -
Look for the settings at the bottom (usually under Options).
-
Add the option for Include Input Fields (or Send Input Data, depending on your exact n8n version) and toggle it ON.
-
This tells the HTTP node to merge the newly fetched status with the
countervariable coming from the previous loop, allowing your JavaScript to finally see the incremented number.
Here are 2 other ways to fix the problem:
- 1: Use n8n’s built-in $runIndex - No Code
You actually don’t need the Code node at all. n8n natively tracks how many times a node has executed during a workflow using the $runIndex variable.
-
Delete the Code node.
-
In your If node, change the Condition to use an Expression:
{{ $runIndex }} -
Set the operator to
Is larger than or equal to
and your value (e.g.,20).
Because the If node is inside the loop:
$runIndex will automatically output:
(0 ) on the first run,
(1) on the second,
(2) on the third,
and so on.
It is the perfect builtin counter that cannot be overwritten.
-2: Use the API’s data
Take a look at the incoming JSON in your first screenshot. The data returning from your Check status node already contains this field:
"attempts": 2
Does the third-party system you are polling already track the attempt count for you, If so, you can skip the Code node entirely and just set your If node to check {{ $json.attempts }}
I recommend Option 1 or Option 2, they keep your workflow much cleaner.
Let me know how it goes, please!