Skip to content

Instantly share code, notes, and snippets.

@boraseoksoon
Last active December 16, 2022 21:11
Show Gist options
  • Save boraseoksoon/66d03a38483b395a6f8b09c249541a37 to your computer and use it in GitHub Desktop.
Save boraseoksoon/66d03a38483b395a6f8b09c249541a37 to your computer and use it in GitHub Desktop.
debounce
import Foundation
// >= iOS 16
var task: Task<(), Never>?
func debounce(interval: Duration = .nanoseconds(10000),
operation: @escaping () -> Void) {
task?.cancel()
task = Task {
do {
try await Task.sleep(for: interval)
operation()
} catch {
// TODO
}
}
}
for i in 0...1000 {
debounce {
print(i)
}
}
// 0
// 25
// 81
// 1000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment