Switching a relay on and off using "millis()" without interfering with the runtime of the other piece of code

What happens if the signal goes high before the process is done?
I will help you get through this if you want, then add the loop counter to prove it runs non-blocking. A button to toggle halt/resume is another proof of functionality and flexibility.

int trigger;
byte state = 0;
const int threshold = 511;
unsigned long msBegin, msLength;

setup() { whatever }

loop()
{
  switch ( state )
  {
    case 0  :  // waiting for signal
    trigger = analogRead();
    msLength = 5000;
    msBegin = millis();
    if ( trigger > threshold )
    {
      state = 1;
    }
    break;

    case 1  :
    if ( millis() - msBegin < msLength )    return;
    ----- turn the relay on
    msBegin = millis();
    state = 2;
    break;

    case 2  :
    if ( millis() - msBegin < msLength )    return;
    ----- turn the relay off
    state = 0;   // go back to wait for signal
    break;
  }
}