A better way to automate a light switch in HA

Using a delay is ok for a quick and dirty method to time how long a light switch should stay on when triggered by a motion sensor. It does not take into account retriggers or flexible enough to incorporate multiple sensors or trigger methods. Here is an example of a more flexible implementation.

Standard way with delay

#  
#--------------------------------------------------------------------
#  Turn on front door light if motion detected on external 
# sensor and not already on
#--------------------------------------------------------------------
#
    - id: 'TurnOnLaundryLightsIfMotion'
      alias: TurnOn_LaundryLightsIfMotion
      trigger:
      - entity_id: binary_sensor.motionlaundry_occupancy
        platform: state
        to: 'on'
      condition:
      - condition: state
        entity_id: switch.lightlaundry
        state: 'off'
      action:
      - entity_id: switch.lightlaundry
        service: switch.turn_on
      - delay:
          hours: 0
          minutes: 5
          seconds: 0
          milliseconds: 0
      - entity_id: switch.lightlaundry
        service: switch.turn_off
      mode: single

     
     

Better way with re-trigger

#  
#--------------------------------------------------------------------
#  Turn On laundry Lights if Motion
#-------------------------------------------------------------------- 
#
- id: 'TurnOnLaundryLightsIfMotion'
  alias: TurnOn_LaundryLightsIfMotion
  trigger:
  - platform: state
    entity_id: binary_sensor.motionlaundry_occupancy
    to: 'on'
  condition:
  - condition: state
    entity_id: switch.lightlaundry
    state: 'off'
  action:
  - service: switch.turn_on
    data:
      entity_id: switch.lightlaundry
  - service: automation.turn_on
    entity_id: automation.TurnOff_LaundryLightsIfMotion


#  
#---------------------------------------------------------------------
#  Turn off laundry Lights if Motion
#---------------------------------------------------------------------
#
- id: 'TurnOffLaundryLightsIfMotion'
  alias: TurnOff_LaundryLightsIfMotion
  trigger:
  - platform: state
    entity_id: binary_sensor.motionlaundry_occupancy
    to: 'off'
    for:
        minutes: 5
  condition:
  - condition: state
    entity_id: switch.lightlaundry
    state: 'on'
  action:
  - service: switch.turn_off
    data:
      entity_id: switch.lightlaundry
  - service: automation.turn_off
    entity_id: automation.TurnOff_LaundryLightsIfMotion