How to run a loop only once while having constant update on a sensor?

Hi, I need some help figuring out how to have the sound stop after the distance is no longer greater than 300. Right now once it gets to

while(x>300)
    {
      tone(8,500);
    }
    noTone(8);

Heres the full code:

int x;
//const int switchPin = 2;
const int motorPin = 9;
//int switchState =0;

void setup()
{
  Serial.begin(9600);
  pinMode(9,OUTPUT);
  
  delay(5000);
  run();
  

  delay(5000);
  check();

}
void loop()
{


}
void run(){
   digitalWrite(9,HIGH);
  tone(8,500);
  delay(400);
  digitalWrite(9,LOW);
  noTone(8);}
  void check(){
     x= analogRead(2);
    while(x>300)
    {
      tone(8,500);
    }
    noTone(8);
  }

Instead of:

     x= analogRead(2);
    while(x>300)
    {
      tone(8,500);
    }

you mean:

    while((x = analogRead(2)) > 300)
    {
      tone(8,500);
    }

or

    x = analogRead(2);
    while(x > 300)
    {
      tone(8,500);
       x = analogRead(2);
    }

or

    while(analogRead(2) > 300)
    {
      tone(8,500);
    }