Last active
May 26, 2017 10:10
-
-
Save levantAJ/d6e1ad2cad249ec6d75089988c229f08 to your computer and use it in GitHub Desktop.
Remove continuously sequences within a delaying time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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