Question About Home Made Timer Function

Hello Processing friends!

In order to practice creating modular functions I created a timer function that uses milli() to determine if a specific number of seconds have passed.

I added some code that I expected to run while the timer was counting but can’t seem to get the lines to draw.

The
//println(“anything?”)
executes once, but like before, I expected it to execture continuously like the
//println(timerDuration-i);
does when uncommented.

Am I missing something regarding execution order? Or maybe because this code is not in draw() it isn’t running efficiently?

The goal of this is to build out different functions of the timer via a switch.


void setup() {
  size(1200, 1600);
}


void draw() {
  background(175);
}

void keyPressed() {
  if (key == 's') {
    timer(1, 5000);
  }
}


void timer(int x, float y) {
  switch(x) {
   case 1:
     int startTime = millis();
     int currentDuration = millis() - startTime;
     float timerDuration = y;
     println(y/1000 + " sec timer started");
     for (int i = currentDuration; i < timerDuration; i = millis() - startTime) {
       //println(timerDuration-i);
       
      //draw grid as long as timer is going
       display();
     }
     println("time up!");
     startTime = millis();
     break;
   }
}

void display() {
  fill(255);
  strokeWeight(8);
  //println("anything?");
  line (width/2, 0, width/2, height);
  line (0, height/2, width, height/2);
}

1 Like

timer runs only once because it’s called from keyPressed

You need to start the timer here but everything else belongs into draw() (or in another function that’s called from draw())

Also, anything that is drawn in a for loop isn’t put on the screen immediately because draw() updates the screen only once at its end (which happens 60 times per second).

Instead of using a for loop just use the fact that draw is looping automatically and set a marker when time is up (check with if).

Amazing,

Thanks for the info Chrisir!

1 Like

Hello,

The Processing references help to understand elements of an active sketch :

https://processing.org/reference/setup_.html
https://processing.org/reference/size_.html
https://processing.org/reference/frameRate_.html
https://processing.org/reference/draw_.html
https://processing.org/reference/keyPressed_.html

I often glean through these resources for insight, examples and inspiration:

:)