Skip to content

Instantly share code, notes, and snippets.

@calt
Last active November 12, 2020 20:46
Show Gist options
  • Save calt/e0e25a82403bb39d9e46d7ccb07ce6e3 to your computer and use it in GitHub Desktop.
Save calt/e0e25a82403bb39d9e46d7ccb07ce6e3 to your computer and use it in GitHub Desktop.
import Dispatch
final class Debouncer {
private var currentWorkItem = DispatchWorkItem(block: {})
private let interval: TimeInterval
private let queue: DispatchQueue
init(interval: TimeInterval, queue: DispatchQueue = .main) {
self.interval = interval
self.queue = queue
}
func run(action: @escaping () -> Void) {
currentWorkItem.cancel()
currentWorkItem = DispatchWorkItem(block: { action() })
queue.asyncAfter(deadline: .now() + interval, execute: currentWorkItem)
}
func cancel() {
currentWorkItem.cancel()
}
deinit {
currentWorkItem.cancel()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment