I am creating a stopwatch that uses NSTimer and a tableview to keep track of user-created laps. While the stopwatch is running and I am interacting (scrolling) with the tableview, the stopwatch stops counting. As soon as I stop interacting with the tableview, the stopwatch continues from where it stopped, not as if it had never stopped counting. This is not just a simulator issue; I put it on my iPad and the same thing happens. How can I keep the stopwatch counting in the background of the app or prevent it from pausing like this? Thanks in advance.
Asked
Active
Viewed 741 times
2
-
Don't use timers, just save a `Date` object and calculate the time in between. This way the stopwatch app can even be killed but the user can still see his running time. – rckoenes Mar 22 '17 at 16:00
-
1Possible duplicate of [UIScrollView pauses NSTimer until scrolling finishes](http://stackoverflow.com/questions/605027/uiscrollview-pauses-nstimer-until-scrolling-finishes) – dan Mar 22 '17 at 16:06
2 Answers
1
You can add the timer to the application runLoop, so the counter will continue when you are interacting with the ui. Just add the following after you created your timer:
RunLoop.current.add(timer, forMode: RunLoopMode.commonModes)

topsa
- 31
- 1
0
The short answer is that you can't. Timers run on the main thread, and if your app is busy doing something when the "fire date" passes, that occurrence of the timer is skipped.
Instead of using a repeating timer and a counter to figure out the amount of time that has passed, record the time when you want to begin timing, and then compute the amount of time elapsed each time your timer fires. Something like this:
@class myViewController: UIViewController {
var startTime: TimeInterval
weak var timer: Timer?
func startTimer() {
startTime = Date().timeintervalSinceReferenceDate
timer = Timer.scheduledTimer...
}
func timerFired(_ timer: Timer) {
let elapsedTime = Date().timeintervalSinceReferenceDate - startTime
}
}

Duncan C
- 128,072
- 22
- 173
- 272
-
why don't you just store a date (the start date) in `startTime` and get `Date().timeIntervalSince(startTime)` or `startTime.timeIntervalSinceNow` ? – Leo Dabus Mar 22 '17 at 17:02
-