HC-SR04 Ultrasonic Sensor detection problem.

Hello everyone, I have been working on a project I need help with. It is basically a wild cat trap. I work at a animal hospital and have brought my work and hobby together.The hospital I work for spays and neuters wild cats/kittens and helps find homes for them. Not all are "wild" just a term for living outdoors.
The cat trap is a standard wire frame one with a spring door closer mechanism. The trap is now designed with and ultrasonic sensor to detect how far the cat is in the trap ( about 20 cm) and to trigger the spring door to close then latch. My problem is that I would like for the sensor to detect that a cat (or whatever animal) has been at 20cm or less for at least a few seconds. This way I figure will keep the trap from triggering if something just blows across the sensor path in the cage or bug flies the way, etc. Also, once the sensor has detected a animal, signals the close and the door closes to not run again. I don't want the animal to be trapped and the Arduino to keep triggering the 'close' relay and actuator.
I've got everything built assembled and just can't figure out how to get the sensor to detect something at 20 cm or less for at least 4-5 seconds THEN trigger the close. Any code ideas out there?

Thank you in advance to everyone in a wonderful community helping the animals of my community.

Whenever the distance is greater than 20 cm reset a timer:

static unsigned long startTime = 0;
if (distance > 20) 
    startTime = millis();

Whenever the distance is less than 20, check the timer:

else {
    if (millis() - startTime > 5000) {

If the timer has reached the limit (i put in 5 seconds) you trigger the door:

        digitalWrite(doorSolenoidPin, HIGH);
        digitalWrite(doorSolenoidPin, LOW);

And then go into a wait loop until the Reset button is pressed:

        while (1) delay(1000);

I can hear the clicks of an ultrasonic sensor - aren't you worried that might scare the victims patients away?