Skip to content

Instantly share code, notes, and snippets.

@koingdev
Created May 1, 2019 14:39
Show Gist options
  • Save koingdev/6b624e192afcf4d557964d032d503f2a to your computer and use it in GitHub Desktop.
Save koingdev/6b624e192afcf4d557964d032d503f2a to your computer and use it in GitHub Desktop.
Swift Debouncer
/// Return a new function that will be called only once after `delay` time passed between invocation
func debounce(delay: TimeInterval, queue: DispatchQueue = .main, function: @escaping () -> Void) -> () -> Void {
var currentWorkItem: DispatchWorkItem?
return {
currentWorkItem?.cancel()
currentWorkItem = DispatchWorkItem { function() }
queue.asyncAfter(deadline: .now() + delay, execute: currentWorkItem!)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment