Condition met for a time period

Greetings everyone!
How can I code a if-else condition with time period? I want my ultrasonic sensor to do something when a condition met in 5 seconds. Any help from you guys would be much apprreciated. :slight_smile:

void CheckSensorTrash() {    // Method for the Ultrasonic sensor in front to detect Obstacle
  digitalWrite(trig_trash, LOW);
  delayMicroseconds(5);
  digitalWrite(trig_trash, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig_trash, LOW);
  duration = pulseIn(echo_trash, HIGH);
  SensorTrash = (duration/2) * 0.034;

  if (SensorTrash <= 3 && SensorTrash > 0){  // for 5 seconds it should do the statement
  //do something 
  }

Maybe something like:

void CheckSensorTrash() 
{
    static unsigned long
        timerTrashStart;
    static bool
        flagThingDone = false;
        flagTrashFirst = false;
                
    // Method for the Ultrasonic sensor in front to detect Obstacle
    digitalWrite(trig_trash, LOW);
    delayMicroseconds(5);
    digitalWrite(trig_trash, HIGH);
    delayMicroseconds(10);
    digitalWrite(trig_trash, LOW);
    duration = pulseIn(echo_trash, HIGH);
    SensorTrash = (duration/2) * 0.034;

    if (SensorTrash <= 3 && SensorTrash > 0)
    {
        if( !flagThingDone )
        {    
            if( !flagTrashFirst )
            {
                timerTrashStart = millis();
                flagTrashFirst = true;
                
            }//if
            else
            {
                if( (millis() - timerTrashStart) > 5000 )
                {
                    //do thing
    
                    flagThingDone = true;
                    
                }//if
                
            }//else
        }//if
    }//if
    else if( SensorTrash > 5 )
    {
        flagThingDone = false;
        flagTrashFirst = true;
         
    }//elif
    
}//CheckSensorTrash

Store the time (millis()) whenever the condition is NOT met. If millis() - storredTime is ever >= 5000, the condition has been met for five seconds.