I have an NSTimer that acts for the basis of a stopwatch.
- (void)startTimer
{
_startDate = [NSDate date];
_timer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
target:self
selector:@selector(updateTimer)
userInfo:nil
repeats:YES];
}
I need to record lap times, but I am running into the issue that 2 separate lap times should not share any overlap.
i.e if lap 1 starts at 0.0 and ends at 10.0, then lap 2 should start at 10.01
But at the moment when there is lap I just take the current time, to work out both the end of the previous lap and the start of the new one:
- (void)lap
{
NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:_startDate];
timeInterval += _timeElapsed;
_startDate = [NSDate date];
}
I need to save the start/end times of each lap as well as their total length. But I cannot see how to do this without having the start/end times be the same for different laps.
Has anyone run into this issue? Any ideas how I can solve it sensibly. Everything I think of feels very brittle.
If it is a true lap timer, as I understand, then your assumption that two separate laps should have a gap in them ins not accurate. Specifically, the statement:
is incorrect for my understanding of a lap timer. The second lap starts immediately, as the start of lap2 is the same as the stop of lap1. Otherwise, you are losing time with those gaps.
I suggest saving only each individual time. So, if you went 5 laps, there should be size times (five if you always start at zero). You now have a time marking for the begin, and end of each lap.
The total time is 50.53, and the time for the third lap is 10.05 (30.09 – 20.04). The sum of all individual laps should equal the total time.
Now, you easily have the total time and the time for each lap. Pretend these values were stored in an array, you could easily do:
Similarly, you can get the time for the first N laps, with simple subtraction, and you could get the times for specific ranges of laps (i.e., laps 2-4).
Hopefully, that makes sense, and I don’t have too many typos without a compiler to check…