Skip to content

Instantly share code, notes, and snippets.

@cprovatas cprovatas/Throttle.swift
Last active Apr 9, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.