Skip to content

Instantly share code, notes, and snippets.

@pokk
Last active January 18, 2017 04:21
Show Gist options
  • Save pokk/0f5645a75d9b0c7d4e7a447656ca40a2 to your computer and use it in GitHub Desktop.
Save pokk/0f5645a75d9b0c7d4e7a447656ca40a2 to your computer and use it in GitHub Desktop.
Simple Timer

Introduction

How to use the NSTimer in Swift.

Note

  1. parameter repeats: true -> repeat, false -> no repeat.
  2. We don't have to call 'timer.fire()' before NSTimer of the method of scheduledTimerWithTimeInterval. Those will fire automatically.
class SwiftTimer {
var timer: Timer!
let interval: Double = 5
init() {
}
func startTimer() {
// When declare a timer then the timer will start counting directly.
self.timer = Timer.scheduledTimerWithTimeInterval(interval, target: self, selector: #selector(action), userInfo: nil, repeats: false)
}
func stopTimer() {
// Stop the timer counting and cancel it.
self.timer?.invalidate()
self.timer = nil
}
func action() {
// Do something you want.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment