Last active
April 21, 2019 12:00
-
-
Save jimmythai/a9550b620e0eadec9872067e7b5cfe4c to your computer and use it in GitHub Desktop.
Use case: To prevent button from being tapped multiple times
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
| class Throttler { | |
| private var workItem: DispatchWorkItem? | |
| private var previousRun: Date = .distantPast | |
| private let queue: DispatchQueue | |
| private let minimumDelay: TimeInterval | |
| init(minimumDelay: TimeInterval, queue: DispatchQueue = .main) { | |
| self.minimumDelay = minimumDelay | |
| self.queue = queue | |
| } | |
| func throttle(_ block: @escaping () -> Void) { | |
| workItem?.cancel() | |
| workItem = DispatchWorkItem() { [weak self] in | |
| self?.previousRun = Date() | |
| block() | |
| } | |
| let delay = previousRun.timeIntervalSinceNow > minimumDelay ? 0 : minimumDelay | |
| queue.asyncAfter(deadline: .now() + delay, execute: workItem!) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment