How to forcefully end a loop as soon as its condition is unmet?

Hi there. I’ve created a pretty basic automation that does this:

When a toggle changes from OFF to ON:

  • start a WHILE (toggle is on) loop that repeats for ever.

Now, I want to stop the loop as soon as the toggle changes from ON to OFF, and execute several other actions afterwards.

Yet, I’m not sure about how While loops work. I’ve tried appending these end actions outside the While loop, but as far as I understood, the entire sequence will go on until its end, THEN check if the toggle is still ON, and IF NOT, end the repeat loop and move on to the subsequent actions.

Is there a way to immediately stop the loop once the toggle switches from ON to OFF again, and execute other actions afterwards?

For now, my workaround has been creating another automation that triggers when toggle is switched OFF, that disables and stops the former automation (and then re-enables it again, to be run again). It works well, yet it’s quite clunky to setup.

What’s the purpose of this?

Perhaps the better tool for your application is a wait_template.

I had something with a repeat look and a long delay, and hated it because it would wait until the end to fall over.
I changed it to repeat short delays until the max number was hit and if it was interrupted, it would bail quickly.
If this helps at all, the code is here.
HA_Blueprints/Automations/door_open_tts_cloud_say_and_Piper_announcer_Piper_OR_nabu_casa_required.yaml at 2b12188d3388cd5dddfadbf4098980804cc24de1 · SirGoodenough/HA_Blueprints · GitHub.