Controlling a specific action for a defined period of time

Hello,

I’m new to Arduino and still trying to learn the language. I have a question regarding having a specified loop run for a predefined period of time. Up to now, I have been using the millis() method to determine if the elapsed time has exceeded the amount of time allotted. I am wondering if there is a more elegant way to do this. My code works, but it seems very bulky/brute force method to me.

  if (button_state==HIGH){
    Serial.println("pressed");
    while ((endtime-starttime)<=5000){
      
      digitalWrite(7,HIGH);
      digitalWrite(8,LOW);
      analogWrite(10,150);
      endtime=millis();
      
    }
    starttime=millis();
  	endtime=starttime;
    
    while ((endtime-starttime)<=1000){
    digitalWrite(7,HIGH);
    digitalWrite(8,HIGH);
    endtime=millis();
  	}
    starttime=millis();
  	endtime=starttime;
           
    while ((endtime-starttime)<=5000){
  
  	digitalWrite(7,LOW);
  	digitalWrite(8,HIGH);
    loopcount=loopcount+1;
    endtime=millis();
    }
    starttime=millis();
  	endtime=starttime;
    
    while ((endtime-starttime)<=1000){
    digitalWrite(7,HIGH);
    digitalWrite(8,HIGH);
    endtime=millis();
  	}
  }

Get rid of the while loops. Set a global variable to record what step of the process you're in, and store the time that you did that, and then check with millis() each round through loop whether it's time to do something.

    starttime=millis();
  	endtime=starttime;
    
    while ((endtime-starttime)<=1000){

0 is always less than 1000

DrAzzy:
Get rid of the while loops. Set a global variable to record what step of the process you're in, and store the time that you did that, and then check with millis() each round through loop whether it's time to do something.

I'm not sure what you mean by this. Would you mind going in to more detail to help me understand?