Created
March 15, 2018 20:51
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
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