Repeat while
The Repeat while building block runs a group of actions as long as its conditions are met. The conditions are checked before each round. Use it when the actions should keep running while something is true, for example, while a mode is turned on.
Using this building block from the user interface
- Go to Settings > Automations & scenes and select an automation. To edit a script, go to the Scripts tab and select the script.
- In the Then do section of an automation, or the Sequence section of a script, select Add action.
- Select Blocks, then select Repeat while.
- Under While conditions, select Add condition, and add the conditions that must be met for the next round.
- Under Actions, select Add action, and add the actions to repeat.
- Select Save.
Options in the UI
The conditions that are checked before each round. The actions run as long as all conditions are met.
Using this building block in YAML
In YAML, use repeat with while and sequence. This example repeats a script as long as input_boolean.do_something is on, and at most 20 times:
do_something:
sequence:
- action: script.get_ready_for_something
- alias: "Repeat the sequence AS LONG AS the conditions are true"
repeat:
while:
- condition: state
entity_id: input_boolean.do_something
state: "on"
# Don't do it too many times
- condition: template
value_template: "{{ repeat.index <= 20 }}"
sequence:
- action: script.something
while also accepts a shorthand notation of a template condition:
repeat:
while: "{{ is_state('sensor.mode', 'Home') and repeat.index < 10 }}"
sequence:
- action: script.something
Options in YAML
The repeat settings.
The conditions that are checked before each round. The actions run as long as all conditions are met. You can also use a template.
Repeat variable
While the actions repeat, the repeat variable shows which round is running. You can also use it in the conditions:
-
repeat.index: The number of the round:1,2,3, and so on. -
repeat.first:trueduring the first round.
Good to know
- The conditions are checked before each round. If they are not met at the start, the actions don’t run at all.
- To make sure the repeat ends, add a condition on
repeat.index, for example,{{ repeat.index <= 20 }}.