-
-
Notifications
You must be signed in to change notification settings - Fork 28
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add Debouncer type with delay function
- Loading branch information
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import Foundation | ||
|
||
/// A class for delaying and debouncing operations. | ||
public final class Debouncer { | ||
private var timerByID: [String: Timer] = [:] | ||
|
||
/// Initializes a new instance of the `Debouncer` class. | ||
public init() {} | ||
|
||
/// Delays operations and cancels all but the last one when the same `id` is provided. | ||
/// | ||
/// - Parameters: | ||
/// - duration: The time duration for the delay. | ||
/// - id: An optional identifier to distinguish different delays (default is "default"). | ||
/// - operation: The operation to be delayed and executed. | ||
/// | ||
/// 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.timerByID[id] = Timer.scheduledTimer(withTimeInterval: duration.timeInterval, repeats: false) { _ in | ||
operation() | ||
} | ||
} | ||
|
||
/// Delays operations and cancels all but the last one when the same `id` is provided. | ||
/// | ||
/// - Parameters: | ||
/// - interval: The time interval for the delay. | ||
/// - id: An optional identifier to distinguish different delays (default is "default"). | ||
/// - operation: The operation to be delayed and executed. | ||
/// | ||
/// 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.timerByID[id] = Timer.scheduledTimer(withTimeInterval: interval, repeats: false) { _ in | ||
operation() | ||
} | ||
} | ||
} |