buzzer does not work with distance sensor hc-sr04

now i have to other coding now

here is my code:

#include <Servo.h>
#define trigPin 7
#define echoPin 8
#define buzzerPin 2

Servo myservo;
int pos=0;

void setup()
  {
    Serial.begin(9600);
    myservo.attach(11);
    pinMode(trigPin,OUTPUT);
    pinMode(echoPin,INPUT);
    pinMode(buzzerPin,OUTPUT);
  }
  
void loop()
  {
    int duration, distance;
    digitalWrite(trigPin,HIGH);
    delayMicroseconds(1000);
    digitalWrite(trigPin,LOW);
    duration=pulseIn(echoPin,HIGH);
    distance=(duration/2)/29.1;
    Serial.print(distance);
    Serial.println("cm");
    delay(500);
    
    for(pos=0;pos<180;pos+=1)
      {
        myservo.write(pos);
        delay(5);
        
          if(distance > 100)
            {
              digitalWrite(2,LOW);
            }
          else
            {
              digitalWrite(2,HIGH);
            }
       }
  
    for(pos=180;pos>=1;pos-=1)
      {
        myservo.write(pos);
        delay(5);
        
          if(distance > 100)
            {
              digitalWrite(2,LOW);
            }
          else
            {
              digitalWrite(2,HIGH);
            }
       }
  }

i have to combine the 2 code from first post, however it scan the distance every cycle of servo rotate, the 500ms delay of the sensor is ignored. how i solve this problem?