Skip to content

Instantly share code, notes, and snippets.

@levantAJ
Last active May 26, 2017 10:10
Show Gist options
  • Save levantAJ/d6e1ad2cad249ec6d75089988c229f08 to your computer and use it in GitHub Desktop.
Save levantAJ/d6e1ad2cad249ec6d75089988c229f08 to your computer and use it in GitHub Desktop.
Remove continuously sequences within a delaying time
//
// A -> B -> C -> D
// `keepFirst`: A
// `keepLast`: D
//
enum DebouncerType {
case keepFirst
case keepLast
}
final class Debouncer: NSObject {
private var block: (() -> Void)?
private var timer: Timer?
private var type: DebouncerType
private var isKeepingFirst = false
init(type: DebouncerType = .keepLast) {
self.type = type
}
func dispatch(delay: Double = 0.25, block: @escaping (() -> Void)) {
switch type {
case .keepFirst:
guard !isKeepingFirst else { return }
isKeepingFirst = true
block()
case .keepLast:
invalidate()
self.block = block
}
timer = Timer.scheduledTimer(timeInterval: delay, target: self, selector: #selector(Debouncer.callback), userInfo: nil, repeats: false)
}
@objc func callback() {
switch type {
case .keepFirst:
invalidate()
isKeepingFirst = false
case .keepLast:
self.block?()
}
}
func invalidate() {
timer?.invalidate()
timer = nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment