Skip to content

Instantly share code, notes, and snippets.

@simme
Last active July 4, 2017 11:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simme/84eb90565c8b99eb75d03306948c39b1 to your computer and use it in GitHub Desktop.
Save simme/84eb90565c8b99eb75d03306948c39b1 to your computer and use it in GitHub Desktop.
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
func debounce1<T>(delay: DispatchTimeInterval, queue: DispatchQueue = .main, action: @escaping ((T) -> Void)) -> (T) -> Void {
var currentWorkItem: DispatchWorkItem?
return { (p1: T) in
currentWorkItem?.cancel()
currentWorkItem = DispatchWorkItem { action(p1) }
queue.asyncAfter(deadline: .now() + delay, execute: currentWorkItem!)
}
}
func myFuncs(foo: Int) {
print("myfunc1", foo)
}
func testDebounce() {
let queue = DispatchQueue.global(qos: .background)
let fn = debounce1(delay: .milliseconds(300), queue: queue, action: myFuncs)
for i in 0...9 {
fn(i)
Thread.sleep(forTimeInterval: 0.2)
}
}
// This will crash with a "Invalid pointer dequeued from free list" error.
// If the parameter in `myFuncs` is changed to a string and line 20 changed to `fn("\(i)")` it does not crash.
testDebounce()
@vrutberg
Copy link

vrutberg commented Mar 23, 2017

Do you mind if I use this Gist as inspiration for a pull request for inclusion in Dollar? I will of course give attribution to you and this Gist.

https://github.com/ankurp/Dollar

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