Last active
December 16, 2022 21:11
-
-
Save boraseoksoon/66d03a38483b395a6f8b09c249541a37 to your computer and use it in GitHub Desktop.
debounce
This file contains hidden or 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 | |
// >= 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