Skip to content

Instantly share code, notes, and snippets.

@boraseoksoon
Created May 10, 2023 07:33
Show Gist options
  • Save boraseoksoon/75f03c00b5e818b7d8e8c21137f2c880 to your computer and use it in GitHub Desktop.
Save boraseoksoon/75f03c00b5e818b7d8e8c21137f2c880 to your computer and use it in GitHub Desktop.
Swift debounce using DispatchWorkItem
func debounce(delay: TimeInterval, action: @escaping () -> Void) -> () -> Void {
var currentWorkItem: DispatchWorkItem?
return {
currentWorkItem?.cancel()
currentWorkItem = DispatchWorkItem(block: action)
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: currentWorkItem!)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment