Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Debounce function for Swift 3
func debounce(_ action: @escaping () -> Void) {
let lastFireTime = DispatchTime.now()
let dispatchDelay = TimeInterval(0.3)
DispatchQueue.main.asyncAfter(deadline: .now() + dispatchDelay) {
let now = DispatchTime.now()
let when = lastFireTime + dispatchDelay
if now >= when {
action()
}
}
}

Isn't this actually a throttle?

benaubin commented Jan 3, 2018

This looks like a complicated delay, not a debounce.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment