Skip to content

Instantly share code, notes, and snippets.

@boraseoksoon
Created December 16, 2022 21:09
Show Gist options
  • Save boraseoksoon/927be81557fc7704717bf893c9ebdf29 to your computer and use it in GitHub Desktop.
Save boraseoksoon/927be81557fc7704717bf893c9ebdf29 to your computer and use it in GitHub Desktop.
debounce prior to iOS 16
import Foundation
// < iOS 16
var task: Task<(), Never>?
func debounce(seconds: Double = 1.0,
operation: @escaping () -> Void) {
task?.cancel()
task = Task {
do {
try await Task.sleep(seconds: seconds)
operation()
} catch {
// TODO
}
}
}
for i in 0...1000 {
debounce(seconds: 1.0 * 0.00001) {
print(i)
}
}
// 0
// 123
// 1000
extension Task where Success == Never, Failure == Never {
static func sleep(seconds: Double) async throws {
let duration = UInt64(seconds * 1_000_000_000)
try await Task.sleep(nanoseconds: duration)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment