I'm setting up timers to execute code once each one finished. However, it seems that the timing of NSTimer is not completely precise, after a while, the timers seem to finish a little too early.
I've set up the following to test the deviation.
(The start button is done in the Storyboard and linked to.)
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var startButton: UIButton!
//var mainTimer: NSTimer!
var counter: NSTimeInterval = 0.0
@IBAction func startButtonPressed(sender: AnyObject) {
startMainTimer()
startTimers()
}
func startMainTimer() {
let mainTimer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: #selector(ViewController.count), userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(mainTimer, forMode: NSRunLoopCommonModes)
}
func count() {
counter += 0.01
}
func startTimers() {
var lastTimeInterval: NSTimeInterval = 0.0
for _ in 0..<50 {
let timeInterval = lastTimeInterval + 1.0
lastTimeInterval = timeInterval
// Not setting up a repeating timer as intervals would be different in my original project where the deviation will be even worse.
let timer = NSTimer.scheduledTimerWithTimeInterval(timeInterval, target: self, selector: #selector(ViewController.printTime), userInfo: nil, repeats: false)
NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
}
}
func printTime() {
print(counter)
}
}
After while, the timers will be early a tenth of a second or even more. Should I be using NSDate for this to have better timing, or would that be overly complicated? How would the above look with NSDate?
Any help / pointers much appreciated!