Skip to content

Instantly share code, notes, and snippets.

@thexande
Created February 19, 2019 18:06
Show Gist options
  • Save thexande/f5cf44597e42c60c1332fa47e69af403 to your computer and use it in GitHub Desktop.
Save thexande/f5cf44597e42c60c1332fa47e69af403 to your computer and use it in GitHub Desktop.
throttle implementation class in swift
final class Throttler {
private var throttleWorkItems: [AnyHashable: DispatchWorkItem] = [:]
private var lastDebounceCallTimes: [AnyHashable: DispatchTime] = [:]
private let nilContext: AnyHashable = arc4random()
/// Delays a closure execution and ensures no other executions are made during deadline
///
/// - Parameters:
/// - deadline: The timespan to delay a closure execution
/// - context: The context in which the throttle should be executed
/// - action: The closure to be executed
func throttle(deadline: DispatchTime,
context: AnyHashable? = nil,
action: @escaping () -> Void) {
let worker = DispatchWorkItem { [weak self] in
guard let myself = self else { return }
defer {
myself.throttleWorkItems.removeValue(forKey: context ?? myself.nilContext)
}
action()
}
DispatchQueue.global(qos: .background).asyncAfter(deadline: deadline,
execute: worker)
throttleWorkItems[context ?? nilContext]?.cancel()
throttleWorkItems[context ?? nilContext] = worker
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment