Skip to content
aleclarson edited this page Oct 21, 2014 · 1 revision

A Timer calls a closure after x seconds go by.

If you do not call autorelease(), you must retain a Timer yourself.

This class is thread-safe!

let timer = Timer(0.5) {
  // do something after half a second passes...
}

timer.autorelease() // useful for fire-and-forget Timers

timer.repeat(2) // repeat twice

timer.repeat() // repeat until stopped

timer.stop() // stops the Timer immediately. alternatively, you could just set it to nil if the variable is an Optional

timer.fire() // completes the Timer immediately (only if not stopped)

Important: Be wary of reference cycles!

class MyClass {
  var timer: Timer!
  func doSomething () {}
  init () {
    
    timer = Timer(1, doSomething) // this will cause a reference cycle!!!
    
    timer = Timer(1) { [unowned self] in self.doSomething() } // this prevents a reference cycle using a capture list.
    
    timer = Timer(1, doSomething()) // and this prevents a reference cycle using an autoclosure.
  }
}
Clone this wiki locally