Created
January 16, 2019 19:13
-
-
Save IanKeen/e9b66f98848a2b50ea249ce44b4aed81 to your computer and use it in GitHub Desktop.
Simple debouncer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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