Why doesn't the if conditional create a delay of .5 seconds?

edited December 2015 in Questions about Code

I want a delay of 0.5 seconds between the drawing of each larger circle. This doesn't work. Also processing crashes if I leave the commented line in the program.

int diam = 10;

void setup(){ size(640, 480); background(#D3EBF0); stroke(#F0D3E8); strokeWeight(2); noFill(); frameRate(2); noLoop(); while(diam < 100){ if((millis() % 500) == 0){ ellipse(width/2, height/2, diam, diam); diam += 10; } //println(millis()); } }

void draw(){

}

Tagged:

Answers

  • edited December 2015

    You need to place code in draw and remove noLoop();

    int diam = 10;
    
    void setup(){ 
    size(640, 480); 
    background(#D3EBF0); 
    stroke(#F0D3E8); 
    strokeWeight(2); 
    noFill(); 
    frameRate(2); 
    }
    
    void draw(){
    while(diam < 100){ 
    if((millis() % 500) == 0){ 
        ellipse(width/2, height/2, diam, diam); 
        diam += 10; 
            } 
        }
    }
    
  • There's no guarantee that that'll work either - draw is called about 60 times a second but millis might be 499 the one time and 525 the next.

  • In this case, draw is called 2 times per second, because of frameRate(2);. Please, inform if this does not do what you want.

  • Answer ✓

    Koogs is right in what he said and changing the frame rate will not make any difference.

    It is impossible to draw the ellipses with an exact delay of 0.5 seconds. The best you can do to maintain an average delay of 0.5s

    The following code does this my calculating the time for the next ellispe and checking the current time hasn't reached it. Notice that setting the frame rate is no longer needed.

    int diam = 10;
    // The next time to draw an ellipse
    int next_time = 0;
    // Time between ellipses
    int delta_time = 500;
    
    void setup() { 
      size(640, 480); 
      background(#D3EBF0); 
      stroke(#F0D3E8); 
      strokeWeight(2); 
      noFill(); 
      next_time = millis() + delta_time;
    }
    
    void draw() {
      if (millis() >= next_time) {
        next_time += delta_time; // next time to draw ellipse
        if (diam < 100) { 
          ellipse(width/2, height/2, diam, diam); 
          diam += 10;
        }
      }
    }
    
  • Well, with a perfect frame rate of 2fps then every frame is 500ms apart so just draw what you want drawing every frame.

    But it won't be perfect.

    You need to decide on the method to use, framerate or millis. They are at odds with each other here.

  • Thanks to quark for a way to implement a delay with out using frameRate. The problem with using a frameRate or 2 from my point of view is that it would affect the speed of everything else whereas with this method I think that after the circles are drawn everything else could run at a faster pace. Exact timing was not important to me. This solution is good enough. Again thanks.

Sign In or Register to comment.