How can I stop a loop when using a servo with a Key input?
Here is a quick and dirty solution, where each loop() iteration
corresponds to one “start sweeping”/“stop sweeping” cycle:


wait for the “start” command
then sweep back and forth in an infinite loop
stop at any point if you receive the “stop” command


void loop() {
    // Wait for the 'start' command.
    while (Serial.read() != 't')
        continue;

    // Repeatedly sweep back and forth.
    for (;;) {
        for (int pos = 0; pos &lt;= 180; pos += 1) {
            myservo.write(pos);
            delay(3);
            if (Serial.read() == 's') // check for 'stop' command
                return;
        }
        for (pos = 180; pos &gt;= 0; pos -= 1) {
            myservo.write(pos);
            delay(3);
            if (Serial.read() == 's') // check for 'stop' command
                return;
        }
    }
}


Note that this approach has a couple of drawbacks:


As this is blocking code, you cannot easily extend the program to do
other things.
The sweeping runs always start at position 0, instead of resuming
from the position that was current on the last “stop” command.


If you need anything more sophisticated, you should go to a non-blocking
approach based on a Finite State Machine (c.f. jsotola's
comment). Note that you can get away with delay(3);, as it is a quite
short delay, but you would have to break the sweeps into one step per
loop() iteration.

I suggest you give the FSM approach a try: read the tutorial I linked
to, then try to implement it. If you cannot get it to work, you can
always post another question here.