Automation - turn off fan if light is turned off, with "x" minutes delay. But, cancel this automation if is lights turned on again

Seriously, I don’t know why you are doing that.
The following is (more or less) taken straight from the integration documents and assuming you have an automation section set up anyway, does it in 17 lines of two automations, no scripts required : -

automation:
  - alias: bath_fan_on
    trigger:
      - platform: state
        entity_id: light.bath_room_ceiling_light
        to: 'on'
    action:
      - service: light.turn_on
        entity_id: light.bath_room_fan
  - alias: bath_fan_off
    trigger:
      - platform: state
        entity_id: light.bath_room_ceiling_light
        to: 'off'
        for: '00:01:00'
    action:
      - service: light.turn_off
        entity_id: light.bath_room_fan

Looking at your code, it seems to be GUI coded (which is fine) but pads it out somewhat.
It is also considered ‘strange’ to mark your own post as the solution (unless you did all the work) but to ‘mark the post that helped you the most’ achieve your desired result. (probably Dave’s ??? )

Also, not sure why your fan switch is listed under the light domain ? (you can change that if you want)

Hi Mutt,
this is not fan switch, because is zigbee relay connected to philips hue. And homeassistant is integrated with philips hue. This is the possible reason why is my fan relay propagated as a light.

Regarding the flag “Solution.” I sorry for that. I marked post as a solution because I use post from PetrolHead as inspiration and made my own and simplify solution how to do solve my issue.

And for your question about why i cant use two simple automation. The answer is, because in situation:

  1. Turn lights on
  2. Turn fan on
  3. Then I leave from bathroom and turn off my lights
  4. automation turns off my fan after x minutes

All this is ok with one automation, but if happens that, the lights are turned on during the countdown of automation, this countdown is not stopped. It continues to run it. Its not what I wanted. I want to stop countdown when the lights are on again.

Understood on the light.
In that case it’s nice to recognise @PetrolHead 's contribution
:+1:

Edit: the posts PetrolHead linked to, are very old (Nov 2017) and the state (and numeric) trigger platforms have since been extended to include ‘for’ statements. Hence the scripts are no longer required.

The time sensor is something you can add to your configuration.yaml which will let you use templates like I posted.

sensor:
  - platform: time_date
    display_options:
      - 'time'
      - 'date'
      - 'date_time'
      - 'date_time_iso'
      - 'time_date'
      - 'time_utc'
      - 'beat'