Loop and Break
Loop
The Loop block allows you to run sets of API blocks in a loop, much like loops in code. There are 3 types of Loop blocks:
For Each Loop
The For Each loop runs the child blocks for every item in the List of items input in the Loop edit pane.
Access the current item and current loop iteration index inside any of the child blocks using the item.value
and index.value
variables. Note, these variables can be renamed in the Loop edit pane.
For Loop
The For loop runs the child blocks N
times, as defined by the Number of iterations input in the Loop edit pane. Access the current loop iteration index inside any of the child blocks using the index.value
variable. Note, this variable can be renamed in the Loop edit pane.
While Loop
The While loop runs the child blocks while the condition field in the Loop edit pane is true. Access the current loop iteration index inside any of the child blocks using the index.value
variable. Note, this variable can be renamed in the Loop edit pane. Check out this example guide that leverages the While loop to fetch paginated data from an API.
Your loop will run forever if you don’t update the variables that the condition field references. If your condition never becomes false, you will hit Superblocks rate limits and your API will stop running. Read more about API rate limits here.
Loop output
Access the output of the Loop block by referencing its output
property (e.g., Loop1.output
). The Loop block's output is an array with an item for every iteration of the loop. Each item is equal to the output from the last child block.
In the following example, the output of this loop block is 5 items, each of which is the output of Step3
for the iteration of the loop. It ran 5 times because Step1.output
was an array with 5 items.
Loop variables
Loop type | Default variables |
---|---|
For Each | index , item |
For | index |
While | index |
Loop index variables start at 0.
Renaming Loop variables
Inside the Loop edit pane, click the variable name to open an input popover for renaming your variable. After renaming it, the variable will update across all blocks in the Loop where it is referenced.
Advanced - setting Loop variables
If you have an advanced use case that requires updating the item
or index
values in a language block, use item.set(YOUR_VALUE)
and index.set(YOUR_VALUE)
. Just like code, setting the index value with index.set()
will change the loop iteration to the index you’ve set.
Break
The Break block allows you to break out of a loop if a condition is true. It can only be used inside a Loop block. Set the If condition in the Break block edit pane to any code that will result in breaking out of the loop if true.
The Break block has no output.