Skip to content

Instantly share code, notes, and snippets.

@comoc
Created June 16, 2016 13:31
Show Gist options
  • Select an option

  • Save comoc/f0757671ba4cc5a7775219a2c8f5eca3 to your computer and use it in GitHub Desktop.

Select an option

Save comoc/f0757671ba4cc5a7775219a2c8f5eca3 to your computer and use it in GitHub Desktop.
An interval timer.
class IntervalTimer {
enum Status { case STARTED, STOPPED, PAUSED }
var duration: Float = 0.0
var startTime: Float = 0.0
var fraction: Float = 0.0
var isLoop: Bool = false
var status: Status = .STOPPED
func setDuration(sec: Float) {
duration = sec
if duration < 0.0 {
duration = 0.0
}
}
func getDuration() -> Float {
return duration
}
func setLoop(isLoop: Bool) {
self.isLoop = isLoop
}
func getLoop() -> Bool {
return self.isLoop
}
func start(sec: Float) {
if status == .STOPPED {
fraction = 0.0
startTime = sec
}
else {
if status == .PAUSED {
startTime = sec - fraction * duration
} else {
if duration >= FLT_EPSILON {
startTime = sec - fraction * duration
}
else {
startTime = sec
}
}
}
status = .STARTED
}
func stop() {
status = .STOPPED
fraction = 0.0
}
func pause() {
status = .PAUSED
}
func update(sec: Float) {
if status == .STOPPED || status == .PAUSED {
return
}
if duration < FLT_EPSILON {
fraction = 0.0
} else {
fraction = (sec - startTime) / duration
if (isLoop) {
fraction = fraction - floorf(fraction);
} else {
if fraction > 1.0 {
fraction = 1.0
}
}
}
}
func getFraction() -> Float {
return fraction
}
func getStatus() -> Status {
return status
}
func isComplete() -> Bool {
return !isLoop && fraction >= 1.0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment