Created
March 15, 2018 20:51
-
-
Save wojteklu/6af1aa6e4285a3a94c212be8a1554d8a 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
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