Skip to content

Instantly share code, notes, and snippets.

@koke

koke/throttle.swift

Created Apr 11, 2016
Embed
What would you like to do?
class Throttle<T>: NSObject {
let timeout: Double
let callback: T -> Void
var timer: NSTimer? = nil
var buffer: T? = nil
init(timeout: Double, callback: T -> Void) {
self.timeout = timeout
self.callback = callback
}
deinit {
timer?.invalidate()
}
func input(value: T) {
cancel()
buffer = value
resetTimer()
}
func cancel() {
if let timer = self.timer where timer.valid {
timer.invalidate()
}
timer = nil
buffer = nil
}
private func resetTimer() {
timer = NSTimer(timeInterval: timeout, target: self, selector: #selector(fetchTimerDidFire(_:)), userInfo: nil, repeats: false)
}
func fetchTimerDidFire(sender: AnyObject) {
guard let value = buffer else {
return
}
callback(value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.