Created
December 16, 2022 21:09
-
-
Save boraseoksoon/927be81557fc7704717bf893c9ebdf29 to your computer and use it in GitHub Desktop.
debounce prior to iOS 16
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(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