End Routine Under Certain Conditions

I’m trying to figure out a code to end a routine under certain constraints. Specifically I want to end the routine at 2s, if a response is given before 2 seconds. Additionally, I want the routine to end immediately if a response is given after 2s. The minimal trial length should be 2s, and the maximum, 4s.

I have tried to code this various ways, but it seems that I either force end the routine after a response is given, the routine ends at 2 s, or it lasts for the entire 4s duration, regardless of if a response was given or not.
#check for new key responsed if not
keys = event.getKeys( )
if keys: #at least one key
if t > 0 and <=2:
if for_code.status == FINISHED: # I added a blank test component of 2s as a marker
continueRoutine = False
#if t in range(0, 2): # I’ve also tried this method to end the routine, didn’t work
if t >= 2:
continueRoutine = False
#else:
#continueRoutine = True
if ‘escape’ in keys:
core.quit( )
elif t < 2.0:
continueRoutine = True
thisExp.addData(‘RT’, t)
elif t >= 4.0:
continueRoutine = False

Any suggestions?

Thanks,

Emily Hokett

The code is very hard to read when it’s not formatted properly, please edit and add three backticks ``` on the line before and the line after, and make sure it looks right, and people will be more likely to respond.

This is a dupe that was solved on another thread :-/