Timed Events On A Loop

Greetings Everyone! I found a timer class here on the forum and I have been tinkering with it. My goal is to have a series of events loop with the timer active and for the loop to be disabled and enabled. I am wondering if there is a better way to do this? Here is what I have come up with so far, thanks in advance.

Timer timer;
color c;

void setup () {
  timer = new Timer();
  timer.start();
}

void draw() {
  if (timer.running) {
    if (timer.second() < 2) { 
      c = color(0, 120, 0);
    } else if (timer.second() < 4) {
      c = color(0, 190, 0);
    } else if (timer.second() < 6) {
      c = color(0, 255, 0);
    } else if (timer.second() > 6) {
      timer.start();
    }
  } else {
    c = color(120, 0, 0);
  }

  fill(c);
  ellipse(width/2, height/2, 100, 100);
  println(timer.second());
}

void mouseClicked() {
  if (timer.running) {
    timer.off();
  } else {
    timer.start();
  }
}

class Timer {
  int startTime = 0, stopTime = 0;
  boolean running = false;  

  void start() {
    startTime = millis();
    running = true;
  }

  void stop() {
    stopTime = millis();
    running = false;
  }

  void off() {
    startTime = 0;
    stopTime = 0;
    running = false;
  }

  int getElapsedTime() {
    int elapsed;
    if (running) {
      elapsed = (millis() - startTime);
    } else {
      elapsed = (stopTime - startTime);
    }
    return elapsed;
  }

  int second() {
    return (getElapsedTime() / 1000);
  }

  int minute() {
    return (getElapsedTime() / (1000*60)) % 60;
  }

  int hour() {
    return (getElapsedTime() / (1000*60*60)) % 24;
  }
}
1 Like
  void stop() {
    stopTime = millis();
    running = false;
  }

  void off() {
    startTime = 0;
    stopTime = 0;
    running = false;
  }

  int getElapsedTime() {
    int elapsed;
    if (running) {
      elapsed = (millis() - startTime);
    } else {
      elapsed = (stopTime - startTime);
    }
    return elapsed;
  }

Notice that getElasedTime() return different values in the case you call either stop() or off(). In other words, the return value is not consistent as it is not clear what the elapsed time means when running is false. I think you don’t need off() and if you were to remove it, your could would be more consistent. If you have a real functionality for off() (and the value returned by getElapsedTime()), then probably you require adding proper comments or, more likely, change the name of the function so you can tell what reference time you are using to get the time lapsed.

You can check the source code of TimeUtilities, which you can install using the Contribution Manager in the PDE which implements something along the same lines. The code is not complex and you could get some other ideas.

Kf

3 Likes