Last active
October 28, 2017 09:47
-
-
Save zvonicek/e2bd4b88b84970a745fe48bcd61d4780 to your computer and use it in GitHub Desktop.
Will only execute the wrapped function if `delay` has passed without this function being called.
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 debounce<A>(delay:Int, queue:DispatchQueue, action: @escaping ((A)->())) -> (A)->() { | |
var lastFireTime = DispatchTime.now() | |
let dispatchDelay = DispatchTimeInterval.milliseconds(delay) | |
return { state in | |
lastFireTime = DispatchTime.now() | |
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 { | |
action(state) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: