Skip to content

Instantly share code, notes, and snippets.

@denyskoch
Last active August 26, 2018 09:43
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 denyskoch/f0db632f38027a93f38ea2880430bc54 to your computer and use it in GitHub Desktop.
Save denyskoch/f0db632f38027a93f38ea2880430bc54 to your computer and use it in GitHub Desktop.
simple debouncing in swift4
import Foundation
typealias Function = () -> ()
typealias FunctionWrapper = (@escaping Function) -> ()
func debounced(time: TimeInterval, callback: @escaping Function) -> Function {
weak var timer: Timer?
return {
timer?.invalidate()
timer = Timer.scheduledTimer(withTimeInterval: time, repeats: false) { _ in
callback()
}
}
}
func debounced(time: TimeInterval) -> FunctionWrapper {
weak var timer: Timer?
return { callback in
timer?.invalidate()
timer = Timer.scheduledTimer(withTimeInterval: time, repeats: false) { _ in
callback()
}
}
}
let debouncedPrint = debounced(time: 0.5) {
print("yes i am debounced")
}
debouncedPrint()
debouncedPrint()
debouncedPrint()
let debouncer = debounced(time: 0.8)
debouncer {
print("first call")
}
debouncer {
print("second call")
}
debouncer {
print("third call")
}
// OUTPUT:
// yes i am debounced
// third call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment