Skip to content

Commit

Permalink
Add explicit cancel function to Debouncer
Browse files Browse the repository at this point in the history
  • Loading branch information
Jeehut committed Oct 17, 2023
1 parent a44f5b3 commit 741f8e5
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions Sources/HandySwift/Types/Debouncer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public final class Debouncer {
/// This version of `delay` uses a `Duration` to specify the delay time.
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
public func delay(for duration: Duration, id: String = "default", operation: @escaping () -> Void) {
self.timerByID[id]?.invalidate()
self.cancel(id: id)
self.timerByID[id] = Timer.scheduledTimer(withTimeInterval: duration.timeInterval, repeats: false) { _ in
operation()
}
Expand All @@ -32,9 +32,17 @@ public final class Debouncer {
///
/// This version of `delay` uses a `TimeInterval` to specify the delay time.
public func delay(for interval: TimeInterval, id: String = "default", operation: @escaping () -> Void) {
self.timerByID[id]?.invalidate()
self.cancel(id: id)
self.timerByID[id] = Timer.scheduledTimer(withTimeInterval: interval, repeats: false) { _ in
operation()
}
}

/// Cancels any in-flight operations with ghe provided `id`.
///
/// - Parameters:
/// - id: An optional identifier to distinguish different delays (default is "default").
public func cancel(id: String = "default") {
self.timerByID[id]?.invalidate()
}
}

0 comments on commit 741f8e5

Please sign in to comment.