Skip to content

Instantly share code, notes, and snippets.

@hamsternik
Created March 13, 2019 14:03
Show Gist options
  • Save hamsternik/1340057fec7df9664a49af2e2e2b2e82 to your computer and use it in GitHub Desktop.
Save hamsternik/1340057fec7df9664a49af2e2e2b2e82 to your computer and use it in GitHub Desktop.
// MARK: - Throttler
public class Throttler {
private let queue: DispatchQueue = DispatchQueue.global(qos: .background)
private var job: DispatchWorkItem = DispatchWorkItem(block: {})
private var previousRun: Date = Date.distantPast
private var maxInterval: Double
init(seconds: Double) {
self.maxInterval = seconds
}
func throttle(block: @escaping () -> Void) {
job.cancel()
job = DispatchWorkItem() { [weak self] in
self?.previousRun = Date()
block()
}
let delay = maxInterval.isLess(than: Date.second(from: previousRun)) ? 0 : maxInterval
queue.asyncAfter(deadline: .now() + Double(delay), execute: job)
}
}
// MARK: - Date extension
private extension Date {
static func second(from referenceDate: Date) -> Double {
return Date().timeIntervalSince(referenceDate)
}
}
@hamsternik
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment