Break long loop

Hi there,

In my code, sometimes I have to break a long loop, but I can't see how to do it. For example, (this is not my code, but the idea is the same), could I break this while with a keyPressed or mousePressed?

int a, b;

void setup() {
  size(400, 600);
  a = 1;
  b = 1000000;
}

void draw() {
  background(0);
  while (a < b) {
    if (keyPressed == true) {
      a=1000000;
    }
    a++;
    println(a);
  }
  println("Outside the while", a);
  noLoop();
}

Thanks!

Answers

  • No, you can't break a loop based on user input in the way you're describing. Functions like draw() and keyPressed() all happen on the same thread, which means that they happen one after the other. The keyPressed() function won't fire until after draw() is finished, and vice-versa.

    You probably need to refactor your code to not use a loop at all. Perhaps use a counter (or the already available frameCount variable) in your draw() function along with the keyPressed variable?

    It's hard to be more specific without understanding exactly what you're trying to do.

  • Hi Kevin,

    I'm applying some filters to several images. Basically, I have

    for (int h = 0; h < numImagesInFolder; h++) {
       // the filters to the images
    }
    

    I configure the filters with some controlP5 controls. If I start processing the images, I can't cancel the process until all the images are filtered. Sometimes I don't like the result after watching 4 or 5 images, and I would like to stop the process.

    I see it is more complicate than I thought.

    Best, f.-

  • Draw() is a loop. Filter one image per draw loop. You can use keyPressed() to stop this.

Sign In or Register to comment.