Last active
April 21, 2019 12:12
-
-
Save jimmythai/fad48770109b74893c12513a701c5fcd to your computer and use it in GitHub Desktop.
Use case: To prevent button from being tapped multiple times
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
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