0

I'm using Java within a Processing project. I'm trying to make a delay that doesn't stop the program, but stops only a given block of code. That "processing" block of code could for example add 1 to a variable, then wait one second and then add 1 again. The problem is that delay() (see reference) stops the whole program and Thread.sleep() doesn't work in a Processing project.

Petr Bodnár
  • 496
  • 3
  • 14
EricZeBaws 2
  • 11
  • 1
  • 2
  • Processing is running with a main loop, right? You could simply get the timestamp at the start. Then, whenever you need the value of that counter (that, as you said, should be increased by 1 every second), you check the timestamp again and can easily calculate how many seconds have passed (= your counter). – domsson Jun 15 '17 at 14:25
  • How would I do that I am new to java and I just started on monday. – EricZeBaws 2 Jun 15 '17 at 14:29
  • With [`Timestamp.getTime()`](https://docs.oracle.com/javase/7/docs/api/java/sql/Timestamp.html) - not sure if that works in Processing, but I guess it would as Processing is just Java after all? – domsson Jun 15 '17 at 14:31
  • And otherwise you could use the time & data functions provided by Processing, see the [reference](https://processing.org/reference/) – domsson Jun 15 '17 at 14:33
  • What's stopping you from creating a new thread and executing the delay() there ? https://processing.org/reference/thread_.html – metodski Jun 15 '17 at 14:43
  • what import would I use for the timestamp – EricZeBaws 2 Jun 15 '17 at 14:46
  • A "funny" way I have done this is creating a method `myDelay()` that runs a `for` loop (with a relatively big number) that does no operation at all, thus, just delaying the execution. – DarkCygnus Jun 15 '17 at 17:34
  • Did you ever get this figured out? – Kevin Workman Jan 03 '18 at 21:42

1 Answers1

0

You should not use delay() or Thread.sleep() in Processing unless you're already using your own threads. Don't use it on the default Processing thread (so don't use it in any of the Processing functions).

Instead, use the frameCount variable or the millis() function to get the time that your event starts, and then check that against the current time to determine when to stop the event.

Here's an example that shows a circle for 5 seconds whenever the user clicks:

int clickTime = 0;
boolean showCircle = false;

void draw(){
  background(64);
  if(showCircle){
    ellipse(width/2, height/2, width, height);

    if(clickTime + 5*1000 < millis()){
      showCircle = false;
    }
  }
}

void mousePressed(){
  clickTime = millis();
  showCircle = true;
}

Side note: please try to use proper punctuation when you type. Right now your question is just one long run-on sentence, which makes it very hard to read.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107