Last active
October 28, 2017 09:49
-
-
Save zvonicek/bf5e420f11c8ebe2c80d4a17ac322719 to your computer and use it in GitHub Desktop.
Will throttle the execution to once in every `delay` seconds.
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
func throttle<A>(delay:Int, queue:DispatchQueue, action: @escaping ((A)->())) -> (A)->() { | |
var lastFireTime = DispatchTime.now() | |
let dispatchDelay = DispatchTimeInterval.milliseconds(delay) | |
return { state in | |
let dispatchTime: DispatchTime = DispatchTime.now() + dispatchDelay | |
queue.asyncAfter(deadline: dispatchTime, execute: { | |
let when: DispatchTime = lastFireTime + dispatchDelay | |
let now = DispatchTime.now() | |
if now.rawValue >= when.rawValue { | |
lastFireTime = DispatchTime.now() | |
action(state) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: