psychopy.org | Reference | Downloads | Github

Breaking out of a loop in the middle of a loop - Javascript

How do I break out the loop immediately, even if the routine in which I am breaking out of the loop is in the middle of the loop? In my experiment, I am able to exit a loop only after going through the remaining routines in the loop, but I would like to be able to exit the loop and move on to routines outside of the loop right after the routine in which the loop is ended.

My code looks like this:

if (key_resp.keys == 1) {
    continueRoutine = false;
    
}

if (key_resp.keys == 2) {
    trials.finished = true;
    continueRoutine = false;
    }
if (key_resp.keys == 1) {
    continueRoutine = false;
} else if (key_resp.keys == 2) {
    trials.finished = true;
    continueRoutine = false;
    }

But I think that’s not what you meant. The issue is that when you set trials.finished = true it always runs all the way to the end of the current loop rather than stopping the loop execution altogether? That’s going to require skip code in the “each frame” panel of a code component in every trial you would need to skip. Basically, in each trial you would want to skip, add this to a code component in the each frame tab:

if (trials.finished === true){
    continueRoutine = false;
}

If this doesn’t work you might just need to make a custom boolean, say “skipTrials” and check that instead of the status of the trial loop.

1 Like