How to replace the delay() function in my code?
The first set of delaymicroseconds for measuring is fine. 

you'll want to replace the delay(5000) when switching the leds.

  if(distance1&gt;20 || distance2&gt;20){
    digitalWrite(led1,LOW);
    digitalWrite(led2,LOW);
  }
  else if(distance1&lt;20){
    digitalWrite(led1,HIGH);
    delay(5000);
  }

  else if(distance2&lt;20){
    digitalWrite(led2,HIGH);
    delay(5000);
  }


you can do that by using a timestamp of when the distance was last high:

  if(distance1&lt;20){
    digitalWrite(led1,HIGH);
    timestamp1 = millis();
  }

  if(distance2&lt;20){
    digitalWrite(led2,HIGH);
    timestamp2 = millis();
  }

if(millis() - timestamp1 &gt; 5000){
  digitalWrite(led1,LOW);
}

if(millis() - timestamp2 &gt; 5000){
  digitalWrite(led2,LOW);
}


timestamp1 and timestamp2 should be globals (or static locals). This code will delay turning off the led to 5 seconds after the sensor last detected something close.