Skip to content

Instantly share code, notes, and snippets.

@zvonicek
Last active October 28, 2017 09:47
Show Gist options
  • Save zvonicek/e2bd4b88b84970a745fe48bcd61d4780 to your computer and use it in GitHub Desktop.
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.
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)
}
})
}
}
@zvonicek
Copy link
Author

Example:

let debouncedPrint: (String) -> () = debounce(delay: 1000, queue: DispatchQueue.main) { text in
    print(text)
}

// ...

debouncedPrint("hello")

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