Skip to content

Instantly share code, notes, and snippets.

@jimmythai
Last active April 21, 2019 12:12
Show Gist options
  • Save jimmythai/fad48770109b74893c12513a701c5fcd to your computer and use it in GitHub Desktop.
Save jimmythai/fad48770109b74893c12513a701c5fcd to your computer and use it in GitHub Desktop.
Use case: To prevent button from being tapped multiple times
extension DispatchQueue {
func throttle(delay: DispatchTimeInterval) -> (_ block: @escaping () -> Void) -> Void {
var lastFireTime: DispatchTime = .now()
return { [weak self, delay] block in
let deadline: DispatchTime = .now() + delay
self?.asyncAfter(deadline: deadline) { [delay] in
let now: DispatchTime = .now()
let when: DispatchTime = lastFireTime + delay
if now < when { return }
lastFireTime = .now()
block()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment