Executing 2 functions simultaneously

I've got a scenario where I want to rotate a servo whilst checking to see if a light value has been met.
At the moment, I'm doing this in a while look, but the Servo doesn't finish executing before it loops again

My checkForNewMessage function needs to wait for the delay as its calling an endpoint and I dont want to spam it

void spinServo() {
    servoRunning = true;
    myservo.write(90);
    delay(1000);
    myservo.write(180);
    delay(1000);
    myservo.write(0);
    servoRunning = false;
}
 
void loop() {
 
  if (WiFi.status() != WL_CONNECTED) {
    wifiConnect();
  }
 
 // If no new message, check for new message
  if(!newMessage) {
    checkForNewMessage();  
  }
 
 
  //This will keep running if a message is unread and the lid is closed
  while(newMessage) {
    if(!servoRunning) {
      spinServo();
    }
   
    lightValue = analogRead(0);
    Serial.println("New Message");
    Serial.println(lightValue);
    //If the lid is opened, the message is read
    if(lightValue > lightValueThreshold) {
        Serial.printf("Analog read value (LDR) %d above threshold of %d -> consider message read.\n", lightValue, lightValueThreshold);
        markAsRead();
        servoRunning = false;
    }
  }
 
  // Wait X seconds
  delay(fetchIntervalMillis);
}

delay( ) bad !

look at BlinkWithoutDelay( ) example

ieee488:
delay( ) bad !

look at BlinkWithoutDelay( ) example

Dont think the delay has anything to do with this though. It's running inside a while loop, and has a boolean whether or not to set trigger the servo function

Hi K20Evo,

Don't think the delay has anything to do with this though.

Delay has a great deal to do with this. While delay() is delaying nothing else is happening, including checking if your light values are met, or anything else.

To fix this you need to get rid of the delays and base your timing on millis() and you need to learn how to do 2 things at the same time. Two good tutorial are:

Using millis for timing
Demonstration for several things at the same time

I would get rid of the while loop as well as this is a blocking function. As long as the while is true nothing else can happen. Consider using the simple timer library