# How to increment a variable on a timer?

**URL:** <https://discourse.processing.org/t/how-to-increment-a-variable-on-a-timer/17984>\
**Category:** Coding Questions\
**Created:** [February 21, 2020, 8:40pm UTC](https://discourse.processing.org/t/how-to-increment-a-variable-on-a-timer/17984 "2020-02-21T20:40:30Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![abc](https://avatars.discourse-cdn.com/v4/letter/a/2bfe46/32.png) [@abc](https://discourse.processing.org/u/abc)\
**Post date:** [February 21, 2020, 8:40pm UTC](https://discourse.processing.org/t/how-to-increment-a-variable-on-a-timer/17984/1 "2020-02-21T20:40:30Z")

</div>

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.

```auto
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);
};

```

---

<div class="post-metadata">

**Author:** ![Chrisir](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/chrisir/32/45_2.png) [@Chrisir](https://discourse.processing.org/u/Chrisir)\
**Post date:** [February 21, 2020, 8:50pm UTC](https://discourse.processing.org/t/how-to-increment-a-variable-on-a-timer/17984/2 "2020-02-21T20:50:01Z")

</div>

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

```auto

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/](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().

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

```

Chrisir
