Skip to content

Instantly share code, notes, and snippets.

@brandFromNSK
Created April 27, 2021 07:50
Show Gist options
  • Save brandFromNSK/cfc394337970332be5788d7eb418ae8e to your computer and use it in GitHub Desktop.
Save brandFromNSK/cfc394337970332be5788d7eb418ae8e to your computer and use it in GitHub Desktop.
final class Debouncer {
private let queue: DispatchQueue
private let delay: TimeInterval
private var workItem: DispatchWorkItem?
init(
delay: TimeInterval,
queue: DispatchQueue
) {
self.delay = delay
self.queue = queue
}
func debounce(_ block: @escaping () -> Void) {
workItem?.cancel()
let newItem = DispatchWorkItem {
block()
}
workItem = newItem
queue.asyncAfter(deadline: .now() + Double(delay), execute: newItem)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment