Basic questions possibly related to how Draw() works

Hi Everyone,

I’m new to Processing and can’t figure out a couple things about the code below.

  1. When I execute the code, it draws either one line or no line at all. Maybe one out of every 4 or 5 runs actually draws a line. Why is that?

  2. Why does it only draw one line (or none), despite the fact that x is incrementing? The code “x = x + 20;” is right before “line (0,800,x,0);”.

I’m sure I’m missing something really basic. Can someone please explain?

Thanks!


int time = 0;
int x = 20;

void setup()
{
  size (1200, 800);
  noSmooth();

  background(255);
  
}
void draw()
{
 
  while (x < 1200)
  {
    if ( millis() > time )
    {
      time = millis() + 500;
      x = x + 20;
      line (0,800,x,0);
      println(x);
     }
  }
}

Because time is set to be greater than millis() almost immediately depending on how fast it is executed. Then x only increments every 500ms, and you get stuck in the while loop waiting for x to equal the exit condition. You’ll only see a line after the while loop ends, so the fastest that would happen is after 30 seconds. The only weird thing is why there is a line at all before 30 seconds has finished.

Edit: Really annoying that edit changes are saved.

avoid using while() inside the draw() loop, your canvas isn’t updated with your draw until each iteration of draw() ends, if you get stuck inside the while() loop you won’t draw anything untill you exit it. :wink:

1 Like