Skip to content

Instantly share code, notes, and snippets.

@marinbenc
Last active July 28, 2017 21:33
Show Gist options
  • Save marinbenc/b5467a89275cab7907eb3f62488e4076 to your computer and use it in GitHub Desktop.
Save marinbenc/b5467a89275cab7907eb3f62488e4076 to your computer and use it in GitHub Desktop.
An action that will be debounced after a certain time in Swift.
import Foundation
/// An action that will get executed after a certain amount of
/// time, if the object is still alive. If the object gets
/// deinited before the provided time, the action will never
/// get executed.
class DebouncedAction {
private let action: ()-> Void
private var onCancel: (()-> Void)?
private let seconds: Int
private let queue: DispatchQueue
init(
dispatchAfterSeconds seconds: Int,
queue: DispatchQueue = .main,
onCancel: (()-> Void)? = nil,
action: @escaping ()-> Void)
{
self.action = action
self.queue = queue
self.seconds = seconds
self.onCancel = onCancel
}
func start() {
let deadline = DispatchTime.now() + DispatchTimeInterval.seconds(seconds)
queue.asyncAfter(deadline: deadline) { [weak self] in
self?.action()
}
}
deinit {
onCancel?()
}
}
// MARK: - Usage:
var debouncedAction: DebouncedAction?
debouncedAction = DebouncedAction(
dispatchAfterSeconds: 1,
onCancel: {
print("Cancelled!")
},
action: {
print("Hey 1")
})
debouncedAction?.start()
debouncedAction = DebouncedAction(dispatchAfterSeconds: 1) {
print("Hey 2")
}
debouncedAction?.start()
// Console output:
// Cancelled!
// Hey 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment