Last active
March 7, 2023 11:09
-
-
Save brandFromNSK/6ea15c5828e95bd43f7fdfd14d78d1cf 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
final class Throttler { | |
private let queue: DispatchQueue | |
private let delay: TimeInterval | |
private var workItem: DispatchWorkItem? | |
private lazy var previousRunDate = Date() | |
init( | |
delay: TimeInterval, | |
queue: DispatchQueue | |
) { | |
self.delay = delay | |
self.queue = queue | |
} | |
func throttle(_ block: @escaping () -> Void) { | |
workItem?.cancel() | |
let newItem = DispatchWorkItem { [weak self] in | |
self?.previousRunDate = Date() | |
block() | |
} | |
workItem = newItem | |
let timeIntervalSincePreviousRun = Date().timeIntervalSince(previousRunDate) | |
if timeIntervalSincePreviousRun > delay || timeIntervalSincePreviousRun < 0 { | |
queue.async(execute: newItem) | |
previousRunDate = Date() | |
} else { | |
queue.asyncAfter(deadline: .now() + Double(delay - timeIntervalSincePreviousRun), execute: newItem) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment