Skip to content

Instantly share code, notes, and snippets.

@Exey
Last active November 27, 2019 22:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Exey/57684442f6244dfed6d9546784db19b9 to your computer and use it in GitHub Desktop.
Save Exey/57684442f6244dfed6d9546784db19b9 to your computer and use it in GitHub Desktop.
Debouncer with Argument
import Foundation
// Debouncer
func debounce(delay: TimeInterval, action: @escaping (String)->Void) -> (String)->Void {
let callback = DebounceCallback(action)
var timer: Timer?
return { arg in
if let timer = timer { timer.invalidate() } // invalidate the last timer
timer = Timer(timeInterval: delay,
target: callback,
selector: #selector(DebounceCallback.exec),
userInfo: ["arg": arg], repeats: false)
if let t = timer { RunLoop.current.add(t, forMode: .default) }
}
}
class DebounceCallback {
let handler: (String)->Void
init(_ handler: @escaping (String)->Void) { self.handler = handler }
@objc func exec(t:Timer) {
if let info = t.userInfo as? [String:String], let arg = info["arg"] { handler(arg) }
}
}
// Test
final class Test {
lazy var debouncedMyFunc: (String) -> Void = debounce(delay: 0.5, action: self.myFunc)
init() {
debouncedMyFunc("0")
debouncedMyFunc("1")
debouncedMyFunc("2")
debouncedMyFunc("3")
debouncedMyFunc("4")
debouncedMyFunc("5")
debouncedMyFunc("6")
debouncedMyFunc("7")
debouncedMyFunc("8")
debouncedMyFunc("9")
}
func myFunc(text: String) {
print("DEBOUNCED \(text)")
}
}
Test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment