Last active
August 26, 2018 09:43
-
-
Save denyskoch/f0db632f38027a93f38ea2880430bc54 to your computer and use it in GitHub Desktop.
simple debouncing in swift4
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
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() | |
} | |
} | |
} |
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
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