Last active
February 27, 2020 12:09
-
-
Save Mildwhale/1261505d2dd530e722959c5f3d615f23 to your computer and use it in GitHub Desktop.
This file contains 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
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