I am trying to calculate the time it takes a vehicle to go between two checkpoints. I have setup the following timer to achieve this.
func startTimer() {
if hasStarted == true && timerStarted == false {
print("Timing started!")
gameTimer = Timer.scheduledTimer(timeInterval: 0.001, target: self, selector: (#selector(activeTiming)), userInfo: nil, repeats: true)
timerStarted = true
}
}
@objc func activeTiming() {
print("Active timing block")
if(hasFinished == false) {
gameTime = gameTime + 0.001
print("Add time succeeded")
} else {
gameTimer?.invalidate()
}
}
The expected output would be the following:
Timing started!
Active timing block
Add time succeeded
Add time succeeded ... etc
The actual output:
Timing started!
So it would appear that the startTimer is properly being called but the timer is not firing the activeTiming block of code. Any suggestions would be extremely helpful. Thank you for your help in advance.
Your code works for me, but that isn't how you want to time an event because the Timer
isn't that accurate, and you are wasting a lot of computing time (read battery).
Instead, I suggest the following approach:
When the event starts, record the start time:
let startTime = Date()
When the event ends, compute the elapsed time:
let elapsedTime = Date().timeIntervalSince(startTime)
elapsedTime
will be in seconds (including fractional seconds).