Skip to content

Instantly share code, notes, and snippets.

@cprovatas
Last active April 9, 2018 19:46
Show Gist options
  • Save cprovatas/07a80afe2d7dbe8269c2f58ce75d5087 to your computer and use it in GitHub Desktop.
Save cprovatas/07a80afe2d7dbe8269c2f58ce75d5087 to your computer and use it in GitHub Desktop.
Throttle , similar to RxSwift's throttle but can be used on any arbitrary block
/// throttle a procedure for the given time interval, operation identifer is used to uniquely identify operation to prevent from firing multiple times
private var throttledOperations: Set<String> = []
func dispatchThrottle(_ interval: TimeInterval, operationIdentifier: String, queue: DispatchQueue = .main, _ closure: @escaping () -> Void) {
guard !throttledOperations.contains(operationIdentifier) else { return }
throttledOperations.insert(operationIdentifier)
closure()
queue.asyncAfter(deadline: .now() + interval) {
throttledOperations.remove(operationIdentifier)
}
}
//usage:
dispatchThrottle(2, operationIdentifier: "MyUniqueBlock") {
debugPrint("this block will execute only once within the given 2 second window")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment