Help with Serial.read code.

I am very new to Arduino. I am working toward building a circuit that flashes LEDs in different patterns based on commands that are sent to it via serial/USB. Here is a basic code as an example:

void loop () {
  if( Serial.available() ) {
    val = Serial.read();
    if( val == 'R' ) { // flash red LED
      digitalWrite(ledRed, HIGH);
      delay(500);
      digitalWrite(ledRed, LOW);
      delay(500);
    }
    if( val == 'B' ) { // flash blue LED
      digitalWrite(ledGrn, HIGH);
      delay(500);
      digitalWrite(ledGrn, LOW);
      delay(500);
    }
    if( val == 'X' ) { // no LEDs on
      digitalWrite(ledRed, LOW);
      digitalWrite(ledGrn, LOW);
    } 
  }

It works as it should, but the LEDs flash on and off only once. Is there a way I can modify the code so that, for example, "R" makes the red LED flash on and off in an infinite cycle until another command is sent?

The BlinkWithoutDelay example should give you some ideas. Basically, what you want is a state machine - no lights flashing state, red lights flashing, and blue lights flashing. Serial input changes the state. The rest of loop flashes the lights according to the state you are in.

The blink without delay example show you how to use millis() to determine whether to turn an LED on or off. Extending that to determine whether to turn a red LED or a blue LED or no LED on or off is pretty simple.

void loop () 
{
  if( Serial.available() )
  {
    val = Serial.read();
  }
    if( val == 'R' ) { // flash red LED
      digitalWrite(ledRed, HIGH);
      delay(500);
      digitalWrite(ledRed, LOW);
      delay(500);
    }
    if( val == 'B' ) { // flash blue LED
      digitalWrite(ledGrn, HIGH);
      delay(500);
      digitalWrite(ledGrn, LOW);
      delay(500);
    }
    if( val == 'X' ) { // no LEDs on
      digitalWrite(ledRed, LOW);
      digitalWrite(ledGrn, LOW);
    }
  }

Would do it.

PaulS's comment aside, you pretty much allready have what you want..
You just needed to move some of your logic (as I've done in the above snippet by adding a curly bracket, you were missing the ending one for loop in your snippet btw).

That did it. Thanks Imahilus.

And PaulS too. I've never really thought to experiment with the BlinkWithoutDelay sketch until now, it should come in handy for other things I'm doing.