How to delay the state update

Hi All,

I have the below template switch using IR to turn off a Soundbar and monitoring the USB power to tell when it is on and off. Currently this is working except when I turn off the device from HA the state of the switch changes to off for a second, then back on, and then off. I’m assumnig there is a slight delay in powering down the USB port so it is not instant. I am trying to find a way to tell the switch to wait for around 1 second before updating the state to prevent the on/off toggling effect. I tried the “delayed_off” filter on the binary sensor but this had the opposite effect and increased the toggling period.

binary_sensor:
  - platform: gpio
    pin:
      number: GPIO25
      inverted: true
      mode:
        input: true
        pullup: true
    id: usb1
    internal: true
switch:
  - platform: template
    name: Sound Bar
    id: sound_bar
    lambda: |-
      if (id(usb1).state) {
        return true;
      } else {
        return false;
      }
    turn_on_action:
      then:
        - remote_transmitter.transmit_pioneer:
            rc_code_1: 0x8010
        - remote_transmitter.transmit_pioneer:
            rc_code_1: 0x804F
            repeat:
              times: 15
    turn_off_action:
        - remote_transmitter.transmit_pioneer:
            rc_code_1: 0x8010

try this

binary_sensor:
  - platform: gpio
    pin:
      number: GPIO25
      inverted: true
      mode:
        input: true
        pullup: true
    id: usb1
    internal: true
    on_state:
      then:
        - if:
            condition:
              for:
                time: 5s
                condition:
                  binary_sensor.is_on: usb1
            then:
              -  switch.turn_on: sound_bar

        - if:
            condition:
              for:
                time: 5s
                condition:
                  binary_sensor.is_off: usb1
            then:
              -  switch.turn_off: sound_bar

    
    
switch:
  - platform: template
    name: Sound Bar
    id: sound_bar
    turn_on_action:
      then:
        - remote_transmitter.transmit_pioneer:
            rc_code_1: 0x8010
        - remote_transmitter.transmit_pioneer:
            rc_code_1: 0x804F
            repeat:
              times: 15
    turn_off_action:
        - remote_transmitter.transmit_pioneer:
            rc_code_1: 0x8010

I tried this YAML out but now the state of the switch is not being updated. It just always shows as off. Below is the original configuration and you can see it turns back on before turning off.
Record_2022-06-22-18-11-19

I think without the lambda optimistic needs to be added

switch:
  - platform: template
    name: Sound Bar
    id: sound_bar
    optimistic: true