Created
March 13, 2019 14:03
-
-
Save hamsternik/1340057fec7df9664a49af2e2e2b2e82 to your computer and use it in GitHub Desktop.
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
// 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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
using source code from here: http://danielemargutti.com/2017/10/19/throttle-in-swift/