How to increment a variable on a timer?

My goal was to make the background color change every 4 seconds, yet I can’t seem to figure out what I should use to allow my variable to continuously increase, right now the color stays the same.

what do I need to add to this code, or what am I not understanding? Any help would be appreciated.

int x = 200;

void setup(){
size(800, 800);
int s = 1; //initial value for s 
while (s < 10000){ s = s + 200;} // i want the s value to continuously increase by
//200, so that the background looks like it's changing color up until this point of
//s = 10000

background(s);

};

void draw(){
rect(x, 40, x, 40);
};
1 Like

Hello and welcome to the forum!

The error lies in the concept of your sketch:

  • setup() runs only once, draw() runs on and on

  • background(s); has a gray color from 0 (black) to 255 (white)

  • a while loop in draw() would not help, since draw() updates the screen only once at its end (once per frame) and not throughout. Instead of a while loop you need to use the fact that draw() in itself loops automatically 60 times per second.

My Suggestion

so try


int x = 200;
int s = 1; //initial value for s

void setup(){
    size(800, 800);
    frameRate(5); 
}

void draw(){
    background(s);
    rect(x, 40, x, 40);
    s = s + 1; 
}

A Timer

look at millis() in the reference to make a real timer.
See https://www.processing.org/reference/
You can say int timer; before setup() and then in setup(): timer = millis(); .

Then check whether more than 4000 milliseconds have passed since you set the timer to millis().

if (millis()-timer > 4000) {
     //
}

Chrisir

2 Likes