NSTimer Example

NSTimer runs a func in a thread’s run loop. It won’t be precise, so account for that.

  1. Create an NSTimer. Pass the non-private name of a func to run when it fires. 
  2. Add the NSTimer to a run loop.
  3. Remember to invalidate the timer when you don’t need the events any more. You’ll need to create a new timer to “resume” since a timer is dead after it is invalidated.
Swift 2.2
var timer: NSTimer?
...
func tick() {
    elapsed = elapsed.advancedBy(1.0)
}
...
timer = NSTimer(timeInterval: 1.0, target: self, selector: #selector(TimerViewController.tick), userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(timer!, forMode: NSRunLoopCommonModes)
...
timer?.invalidate()

Hat tips to: