Skip to content

Instantly share code, notes, and snippets.

@ytyubox
Last active May 1, 2019 14:25
Show Gist options
  • Save ytyubox/345e76aab55ce56ce2893eaed286513b to your computer and use it in GitHub Desktop.
Save ytyubox/345e76aab55ce56ce2893eaed286513b to your computer and use it in GitHub Desktop.
A friendly timer

init timer

let timer:ATimer = Timer.makeFirendlyTimer(for type: .one)
let aClosure:()->Void = {...}
timer.job = aClosure

start timer

timer.start()

End timer

timer.stop()
protocol ATimer {
func start()
func stop()
var isRuning:Bool{get}
var timeInterval:TimeInterval{get set}
typealias Job = ()->Void
}
class AReapeatTimer:ATimer{
var isRuning: Bool {return timer != nil}
init(job: @escaping Job) {
self.job = job
}
init(){}
var timeInterval:TimeInterval = 0.1
var job:Job!
func start(){
timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(timerJob), userInfo: nil, repeats: true)
}
func stop() {
timer?.invalidate()
timer = nil
}
@objc
fileprivate func timerJob() { job() }
fileprivate var timer:Timer?
}
class AOneTimer: AReapeatTimer {
override func start() {
timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(timerJob), userInfo: nil, repeats: false)
}
}
import Foundation.NSTimer
extension Timer{
enum TimerType{
case repeated, one
}
static func makeFirendlyTimer(for type:TimerType) -> ATimer{
var aTimer:ATimer
switch type {
case .repeated:
aTimer = AReapeatTimer()
case .one:
aTimer = AOneTimer()
}
return aTimer
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment