Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Created January 16, 2019 19:13
Show Gist options
  • Save IanKeen/e9b66f98848a2b50ea249ce44b4aed81 to your computer and use it in GitHub Desktop.
Save IanKeen/e9b66f98848a2b50ea249ce44b4aed81 to your computer and use it in GitHub Desktop.
Simple debouncer
func debounce<T>(delay: TimeInterval, function: @escaping (T) -> Void, complete: @escaping () -> Void = { }) -> (T) -> Void {
let queue = DispatchQueue(label: "Debouncer")
var current: DispatchWorkItem?
return { input in
current?.cancel()
let new = DispatchWorkItem {
function(input)
complete()
}
current = new
queue.asyncAfter(deadline: .now() + delay, execute: new)
}
}
struct User {
var name: String
}
var user = User(name: "Ian")
let update = debounce(
delay: 0.5,
function: { (name: String) in
print(name)
user.name = name
},
complete: {
print("New Value:", user.name)
}
)
update("a")
update("b")
update("c")
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
update("d")
update("e")
}
/* OUTPUT:
c
New Value: c
e
New Value: e
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment