DAT301 – Timer

Here is the simple Timer class that I mentioned in the previous post.

// Timer
// author Jo Redwood jred.co.uk

class Timer{
  int period; // milliseconds
  int time;
  int lastTime = 1;
  int timer;
  boolean active = false;
  boolean running = true;

  Timer(int newPeriod){
    period = newPeriod;
  }

  void update(){
    if(running){
      time = millis();
      if(time - lastTime >= period){
        lastTime = time;
        active = true;
        timer = 0;
      }else{
        active = false;
      }
    }
  }

  void setPeriod(int newPeriod){
    period = newPeriod;
  }

  // Resumes the timer
  void start(){
    running = true;
  }

  // Pauses the timer
  void stop(){
    running = false;
  }

  boolean active(){
    return active;
  }
}

Usage:

Timer timer;
void setup(){
  timer = new Timer(500);
}
void draw(){
  timer.update();
  if(timer.active()){
    // Do stuff
  }
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.