Detect keypress while in a loop

I am making a program to make music. However the playfunction has the problem, that I can’t interrupt it. So I wanted to implement a key to abort the play function.

Here is a example to show the problem. It also has the things implemented, that I tried:

boolean abort=false;

void setup() {
  size(200, 200);
}
void doSomeThing() {
  for (int i=0; i<10; i++) if (!abort) {
    //here the note is played.
    println(i);
    delay(500);
    redraw();
    if(keyPressed) if (key=='a') abort=true;
  } else {
    println("Process was aborted");
  }
  abort=false;
}
void draw() {
    if(keyPressed) if (key=='a') abort=true;
}
void keyPressed() {
  if (key=='d') doSomeThing();
  if (key=='a') abort=true;

So how can I detect a key while in a loop?

in this function :

    if(keyPressed) 
        if (key=='a')  { 
            abort=true; 
            return 
        }

worth a shot

but really you should get rid of the for loop and call doSomeThing from draw() when abort==false; 10 times (with a counter to 10)

I think that key is better recognized this way

1 Like

If I understand correctly, I second Chrisir’s idea of merging doSomeThing into draw loop.

Nevertheless, you can also try to use a thread

boolean abort=false;

void setup() {
  size(200, 200);
}
void doSomeThing() {
  for (int i=0; i<10; i++) if (!abort) {
    //here the note is played.
    println(i);
    delay(500);
    redraw();
  } else {
    println("Process was aborted");
  }
  abort=false;
}
void draw() {
}
void keyPressed() {
  if (key=='d') thread("doSomeThing");
  if (key=='a') abort=true;
}

This actually runs, but weird thing can happen if you press d again before aborting the last loop. It is up to your design:

  • when multiple loops are running, a will abort all the loops
  • when multiple loops are running, a will abort only the last loop or
  • prevent multiple loops to run
2 Likes