Skip to content

Instantly share code, notes, and snippets.

@Mildwhale
Last active February 27, 2020 12:09
Show Gist options
  • Save Mildwhale/1261505d2dd530e722959c5f3d615f23 to your computer and use it in GitHub Desktop.
Save Mildwhale/1261505d2dd530e722959c5f3d615f23 to your computer and use it in GitHub Desktop.
import Foundation
final class Debouncer {
private var interval: TimeInterval
private var timer: Timer?
init(interval: TimeInterval) {
self.interval = interval
}
func call(action: @escaping () -> Void) {
resetTimer()
DispatchQueue.main.async {
self.timer = Timer.scheduledTimer(withTimeInterval: self.interval, repeats: false, block: { (_) in
action()
})
}
}
func resetTimer() {
if timer != nil {
timer?.invalidate()
timer = nil
}
}
}
// Sample
class Foo {
private var debouncer = Debouncer(interval: 0.3)
private func doSomething() {
debouncer.call { [weak self] in
self?.fire()
}
}
private func fire() {
print("Fire")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment