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

  1. Go to Settings > Automations & scenes and select an automation. To edit a script, go to the Scripts tab and select the script.
  2. In the Then do section of an automation, or the Sequence section of a script, select Add action.
  3. Select Blocks, then select Repeat while.
  4. Under While conditions, select Add condition, and add the conditions that must be met for the next round.
  5. Under Actions, select Add action, and add the actions to repeat.
  6. Select Save.

Options in the UI

While conditions (Required)

The conditions that are checked before each round. The actions run as long as all conditions are met.

Actions (Required)

The actions to repeat.

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:

ScriptA script is a saved list of steps that runs when you start it, for example, from a dashboard, with Assist, or from an automation. Unlike an automation, a script has no triggers, so it doesn't start by itself. [Learn more]
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:

ActionAn action makes Home Assistant do something, for example, turn on a light, send a notification, or activate a scene. Automations and scripts run a list of actions. [Learn more]
repeat:
  while: "{{ is_state('sensor.mode', 'Home') and repeat.index < 10 }}"
  sequence:
    - action: script.something

Options in YAML

repeat map Required

The repeat settings.

while list | template Required

The conditions that are checked before each round. The actions run as long as all conditions are met. You can also use a template.

sequence list Required

The actions to repeat.

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: true during 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 }}.