Skip to content

Instantly share code, notes, and snippets.

@tstone
Created July 27, 2021 23:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tstone/fee1f58caf9258937bd7eefc7e27802a to your computer and use it in GitHub Desktop.
Save tstone/fee1f58caf9258937bd7eefc7e27802a to your computer and use it in GitHub Desktop.
Timer for VM
package com.collidermodular.util;
public class Timer {
private final double samplesPerMs;
private final Runnable runnable;
private double duration;
private double sampleCounter;
private double targetSampleCount;
private boolean active;
private boolean loop = false;
public Timer(double duration, double samplesPerMs, Runnable runnable) {
this.runnable = runnable;
this.samplesPerMs = samplesPerMs;
this.setDuration(duration);
this.reset();
}
public double getDuration() { return this.duration; }
public double getDurationRemaining() {
if (this.active) {
double samplesRem = targetSampleCount - sampleCounter;
return samplesRem / samplesPerMs;
} else {
return 0.0;
}
}
public boolean isActive() { return this.active; }
public void setDuration(double duration) {
this.duration = duration;
this.targetSampleCount = samplesPerMs * duration;
}
public void trigger() {
this.reset();
this.active = true;
}
public void startLoop() {
this.runnable.run();
this.loop = true;
this.trigger();
}
public void stopLoop() {
this.loop = false;
this.reset();
}
public void reset() {
this.sampleCounter = 0;
this.active = false;
}
public void processSample() {
if (this.active) {
this.sampleCounter += 1;
if (sampleCounter >= targetSampleCount) {
this.runnable.run();
if (this.loop) {
// carry over remainder for more accurate timing between samples
this.sampleCounter = this.sampleCounter - targetSampleCount;
} else {
this.reset();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment