Skip to content

Instantly share code, notes, and snippets.

@AnselmeKotchap
Last active July 23, 2016 07:17
Show Gist options
  • Save AnselmeKotchap/8af2f3cbb7cb9da59f73971efa2e45ec to your computer and use it in GitHub Desktop.
Save AnselmeKotchap/8af2f3cbb7cb9da59f73971efa2e45ec to your computer and use it in GitHub Desktop.
import Foundation
class Timer {
var timer = NSTimer()
var handler: (Int) -> ()
let duration: Int
var elapsedTime: Int = 0
init(duration: Int, handler: (Int) -> ()) {
self.duration = duration
self.handler = handler
}
func start() {
self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0,
target: self,
selector: Selector("tick"),
userInfo: nil,
repeats: true)
}
func stop() {
timer.invalidate()
}
@objc func tick() {
self.elapsedTime++
self.handler(elapsedTime)
if self.elapsedTime == self.duration {
self.stop()
}
}
deinit {
self.timer.invalidate()
}
}
//source: http://samuelmullen.com/2014/07/using-swifts-closures-with-nstimer/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment