Skip to content

Instantly share code, notes, and snippets.

@wojteklu
Created March 15, 2018 20:51
Show Gist options
  • Save wojteklu/6af1aa6e4285a3a94c212be8a1554d8a to your computer and use it in GitHub Desktop.
Save wojteklu/6af1aa6e4285a3a94c212be8a1554d8a to your computer and use it in GitHub Desktop.
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: TimeInterval
public init(maxInterval: TimeInterval) {
self.maxInterval = maxInterval
}
public func throttle(block: @escaping () -> ()) {
job.cancel()
job = DispatchWorkItem(){ [weak self] in
self?.previousRun = Date()
block()
}
let delay = Date().timeIntervalSince(previousRun) > maxInterval ? 0 : maxInterval
queue.asyncAfter(deadline: .now() + Double(delay), execute: job)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment