This little code piece implements a Timer class which takes a duration and countdown, and returns a value in the range [0..1] depending on how much of the specified time has elapsed. The variable “fract” gives the state of the timer, with a value of 0 representing a state in which the timer has not started (i.e. still in countdown interval). A value of 1 means that the countdown is complete and the time specified as duration has elapsed. A fractional value represents how far into the time interval the program has reached.
This is useful for animation in absolute time, regardless of frame rate. The timer’s update() function must be called before using the value contained in the “fract” variable.
// Timer.pde
// Marius Watz - http://workshop.evolutionzone.com
// Takes a duration and countdown given in seconds.
// Returns a value in the range [0..1], 0 representing not started and
// 1 representing time interval complete.
class Timer {
public long start,countdown,duration,durationTotal,elapsed;
public float fract;
// Input: duration and countdown (in seconds)
public Timer(long _dur,long _cnt) {
countdown=_cnt*1000;
duration=_dur*1000;
durationTotal=duration+countdown;
start=System.currentTimeMillis();
}
public void update() {
if(fract>=1) return;
elapsed=System.currentTimeMillis()-start;
if(elapsed< countdown) fract=0;
else if(elapsed>durationTotal) fract=1;
else fract=(float)(elapsed-countdown)/(float)duration;
}
}
// timertest.pde
// Marius Watz - http://workshop.evolutionzone.com
Timer timer;
void setup() {
size(300,300);
// init timer with a duration of 20 sec, countdown 5 sec
timer=new Timer(20, 5);
}
void draw() {
background(0);
// update timer
timer.update();
// use timer value for animation
float rad=20+timer.fract*50;
ellipse(150,150, rad,rad);
}




